Reputation: 11437
I have a Json
file which has unknown child nodes each of which have child nodes for an unknown depth.
I want to get the 1st level of child node names into an array.
How do i do this if i dont know their names or the number of child nodes - ie the json structure is dynamic?
eg json input
{
"childNode1":"value", "childNode2":"value", "childNode3":"value", "childNode4":"value"
}
expected output is equivalent to this array:
string[] jsonArray =
new[] { "childNode1", "childnode2", "childNode3", "childnode4" };
The code i have will show me the children in the debugger 'locals', how can i get their keys and values?
JObject json = JObject.Parse(System.IO.File.ReadAllText(filePath));
I can do it if i know what nodes I'm looking for but i don't in this case?
Upvotes: 0
Views: 1698
Reputation: 35726
you could do,
IEnumerable<string> ParsePropertyNames(string s)
{
var o = JObject.Parse(s);
return o.Properties().Select(p => p.Name);
}
which your could use like,
var results = ParsePropertyNames(yourString).ToArray();
Upvotes: 1
Reputation: 56556
If you deserialize the object as a dictionary, you can get the keys easily. Here's an example using Json.NET.
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(s);
string[] jsonArray = dict.Keys.ToArray();
Depending on what you want to do with the object, the second line might be redundant.
If you already have it as a JObject
, you can get the names like this:
JObject json = // something
string[] jsonArray = ((IDictionary<string, JToken>)json).Keys.ToArray(); // or
string[] jsonArray = json.Properties().Select(x => x.Name).ToArray();
Upvotes: 3