Search code examples
jsonxpathjsonpath

How to find all elements by value in list in JSonPath


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"]}

Solution

  • 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