I am trying to find a path of a JSON value. Consider the following JSON:
{
"car": {
"type": [{
"sedan": {
"make": "honda",
"model": "civics"
}
},
{
"coupe": {
"make": "ford",
"model": "escort"
}
}]
}
}
How can I get the path of the value "honda"? I'm looking to find something like this...
car_type_0_sedan_make_honda
Does JSON.NET support this? I see that there is a JToken.Path property but it is currently not available. http://json.codeplex.com/workitem/24136
JObject obj = JObject. Parse(person); To apply JSONPath expressions we can use the SelectToken method. As input of this method we need to pass a string with the JSONPath expression we want to use and, as output, it will return a JToken with the result (or null, in case nothing is found).
XPath uses it to iterate over element collections and for predicates. In JavaScript and JSON it is the native array operator. | [,] Union operator in XPath results in a combination of node sets.
The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...
JSONPath creates a uniform standard and syntax to define different parts of a JSON document. JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. This topic is best understood by seeing it in action. We have created a web page which can help you evaluate a JSONPath.
You could also try the SelectToken
method like this:
var j = JObject.Parse(json);
var token = j.SelectToken("car.type[0].sedan.make");
Console.WriteLine(token.Path + " -> " + token.ToString());
Outputs:
car.type[0].sedan.make -> honda
Update to the latest version of Json.NET. The Path
property was added to JToken
in version 5.0 release 1 (April 7, 2013).
Here is a test program you can use to verify that it works:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""car"": {
""type"": [{
""sedan"": {
""make"": ""honda"",
""model"": ""civics""
}
},
{
""coupe"": {
""make"": ""ford"",
""model"": ""escort""
}
}]
}
}";
JObject obj = JObject.Parse(json);
JToken token = obj["car"]["type"][0]["sedan"]["make"];
Console.WriteLine(token.Path + " -> " + token.ToString());
}
}
Output:
car.type[0].sedan.make -> honda
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