101

I have some JSON that looks like this

[
  {
    "MobileSiteContent": {
      "Culture": "en_au",
      "Key": [
        "NameOfKey1"
      ]
    }
  },
  {
    "PageContent": {
      "Culture": "en_au",
      "Page": [
        "about-us/"
      ]
    }
  }
]

I parse this as a JArray:

var array = JArray.Parse(json);

Then, I loop over the array:

foreach (var content in array)
{

}

content is a JToken

How can I retrieve the "name" or "key" of each item?

For example, "MobileSiteContent" or "PageContent"

Alex
  • 37,502
  • 51
  • 204
  • 332

6 Answers6

160

JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)

Putting it all together we have:

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        Console.WriteLine(prop.Name);
    }
}

Output:

MobileSiteContent
PageContent
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
33
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"]; 

foreach (JProperty attributeProperty in attributes)
{
    var attribute = attributes[attributeProperty.Name];
    var my_data = attribute["your desired element"];
}
humbads
  • 3,252
  • 1
  • 27
  • 22
Priyanka Lad
  • 351
  • 3
  • 5
29

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}
Kjuly
  • 34,476
  • 22
  • 104
  • 118
Brandin Perry
  • 307
  • 3
  • 2
2

Using Linq we can write something like:

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    List<string> keys = content.Properties().Select(p => p.Name).ToList();
}
Lucian
  • 874
  • 11
  • 33
-1

If the JToken key name is unknown, and you only need the key's Value regardless of name, simply use the JToken.Values() method.

The below sample assumes the JToken value is a primitive type - first value found is extracted.
Solution can be extended to support Array values.

JToken fooToken = sourceData.

int someNum =  fooToken .Values<int?>().First() ?? 0;

int someString =  fooToken .Values<string>().First();
Peter O Brien
  • 105
  • 2
  • 6
-3

The simplest way is to look at the path of each item in the JSON object.

For Each token As JToken In json
        Dim key= token.Path.Split(".").Last
Next
Scott
  • 3,663
  • 8
  • 33
  • 56