I can find a person who has a hobby of “Dance” by doing the following:
Xpath = Persons/Person/Hobbies/Hobby[text()="Dance"]/../..
<Persons>
<Person>
<Name>David</Name>
<Age>20</Age>
<Hobbies>
<Hobby>Sing</Hobby>
<Hobby>Dance</Hobby>
</Hobbies>
</Person>
<Person>
<Name>Frank</Name>
<Age>30</Age>
<Hobbies>
<Hobby>Sing</Hobby>
<Hobby>Read</Hobby>
</Hobbies>
</Person>
</Persons>
How would I do the same for JSONPath? For example, I have this json:
[
{"name": "david", "age": 20, "hobbies": ["dance", "sing"]},
{"name": "frank", "age": 30, "hobbies": ["sing", "read"]}
]
So far I have $[*].hobbies[*]
but I’m not sure how to go further. I am using https://jsonpath.com/ to test. The result I want should be:
{"name": "david", "age": 20, "hobbies": ["dance", "sing"]}
2
Answers
You’ll need to do a nested filter expression query.
The first
[]
syntax gets you inside the outer array.At this point, you need a filter query, which looks at each item. For each item, you want to look at each item of the
hobbies
array, so you need.hobbies
to get that array[]
to get you inside that arraydance
This is not a direct answer to your question, but since you obviously know XPath already, and you raise some question about variation in support for JSONPath, I thought I’d point out that you can also query JSON data in standard XPath 3.1 (the latest version of XPath). e.g.
Applying the following XPath to your JSON array:
Result:
XPath fiddle