How to get the key name in json?

1.5k Views Asked by At

My previous problem was I'm unable to arrange the json structure like what I wanted. And I found some answers that looks like it almost satisfy my needs but unfortunately I don't know if it's working or not because another problem has occurred.

Below, I arranged my own json data based on the json structure by someone named Programmer.

{
    "dialog_type": {"human": {"inner": "He is so scary"}}
}

Here, I have a key called "human". I have two keys in my data. First is "human" and second is "non_human". Now if I have two data in my json file, it will become like this :

{
    "dialog_type": {"human": {"inner": "He is so scary"}}
},
{
    "dialog_type": {"non_human": "Once upon a time..."}
}

This case is maybe simillar to someone asked here. But unfortunately I have no idea if it's possible to do that in unity. I want to make a method like this answer. So I can determine what action to take by comparing those keys.

Now the question is how do I get the key name as a string in my json data using C# ?

1

There are 1 best solutions below

0
On

To access the property names of a Unity javascript object, you can use:

for(var property in obj) {}

For instance, this will log all keys (i.e. property names) of all the property key-value pairs in a Unity javascript object (e.g. "key1" and "key2"):

function Start () {
  var testObject = {
    "key1": "value 1",
    "key2": "value 2"
  };

  for(var property in testObject) {
    Debug.Log(property.Key);
  };
}

That should give you a way to check objects for any matching property names you are interested in.