I am listing down my sample JSON below, I want to write a JSONPath that selects element when subjects has (or contains) "Maths".
NOTE: I am using Goessner's JSONPath using Newtonsoft library (C#)**
{
"class":{
"type":"group",
"identifier":"MyFavClass",
"subs":[
{
"type":"individual",
"identifier":"Rambo"
},
{
"type":"individual",
"identifier":"Rancho"
},
{
"type":"biggroup",
"identifier":"village",
"subjects":[
"Maths",
"English"
]
},
{
"type":"biggroup",
"identifier":"newvillage",
"subjects":[
"Maths"
]
}
]
}
}
Assuming you are using Json.NET's SelectTokens()
method for your JSONPath queries, you may find all math subjects using the following query:
var value = "Maths";
var subjects = root.SelectTokens($"class.subs[*].subjects[?(@ == '{value}')]");
Of course this will just return a sequence of JValue
tokens with value "Maths"
. If you want the class.subs[*]
objects whose subjects[*]
arrays contains "Maths"
, you may do:
var subs = root.SelectTokens($"class.subs[?(@.subjects[?(@ == '{value}')])]");
Notes:
[?(...)]
applies a filter expression ...
to an array.
In a filter expression, array contents that are primitive values may be matched using the @
symbol for the current object.
Json.NET's implementation of JSONPath supports nested queries inside array filter expressions. Thus [?(@.subjects[?(@ == '{value}')])]
matches array items that have an item in their "subjects"
array that matches the value parameter.
Note that search values that contain a single quote character '
must be escaped as shown in Querying JSON with JSON Path and escaped properties . Thus if the string to be matched was Math's
you would need to escape it like so:
var value = "Math's".Replace("'", "\\\'");
Demo fiddle here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.