skip to Main Content

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>

enter image description here

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


  1. You’ll need to do a nested filter expression query.

    $[?(@.hobbies[?@ == 'dance'])]
    

    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
    • another [] to get you inside that array
    • another filter query to check for dance
    Login or Signup to reply.
  2. 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:

    ?*[?hobbies="dance"]
    

    Result:

    {"hobbies":["dance","sing"],"name":"david","age":20}
    

    XPath fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search