I am using NewtonSoft Json.NET library for parsing JSON files in a .NET app. What I need to do is to pass the name of a node, and get the node if it exists, regardless of their level which is unknown beforehand.
For instance in a file:
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""ATest"": {
""MyTest"":
[
""blah"",
""blah""
]
}
}";
Is there a way to just use the value "MyTest"
to fetch that node without having to know the parent's name like jObject["ATest"]["MyTest"][0]
?
AFAIK there's no XPath-like query syntax for JToken
/ JObject
, but you can make one fairly easily - see code below.
public static class StackOverflow_13033174
{
public static void Test()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""ATest"": {
""MyTest"":
[
""blah"",
""blah""
]
}
}";
JObject jo = JObject.Parse(json);
JToken myTest = jo.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "MyTest")
.Select(p => ((JProperty)p).Value)
.FirstOrDefault();
Console.WriteLine(myTest);
}
}
Here is another approach using JSONPath:
See: https://dotnetfiddle.net/EIKjnH
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
public static class StackOverflow_13033174
{
public static void Main()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""ATest"": {
""MyTest"":
[
""blah"",
""blah""
]
}
}";
JObject jo = JObject.Parse(json);
JToken myTest = jo.SelectToken("*.MyTest");
Console.WriteLine(myTest);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With