Getting the name / key of a JToken with JSON.net
Asked Answered
A

6

103

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"

Anthotaxy answered 8/1, 2014 at 17:18 Comment(0)
O
162

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
Overweight answered 8/1, 2014 at 22:28 Comment(0)
A
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"];
}
Abstractionism answered 4/7, 2018 at 8:10 Comment(0)
R
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);
}
Rodenhouse answered 8/5, 2014 at 23:57 Comment(1)
Making the foreach clear: foreach (KeyValuePair<string, JToken> pair in obj)Delorenzo
H
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();
}
Heall answered 7/10, 2022 at 11:52 Comment(0)
M
1
string name = jToken.Path.Split(".").Last();

This worked for me.

Moncrief answered 22/12, 2023 at 9:35 Comment(0)
G
-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
Giselegisella answered 7/3, 2021 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.