Search code examples
jsonjsonata

How retrieve a parent branch based on a value?


I have an array of Fruits. Each Fruit has a name and an array of countries. Each country has a name and a price.

How do I select all fruit names with a price of 12? i.e. go up a branch.

{
    "fruits": [
        {
            "name": "apple",
            "countries": [
                {
                    "name": "japan",
                    "price": "12"
                },
                {
                    "name": "iceland",
                    "price": "83"
                }
            ]
        },

        {
            "name": "oranges",
            "countries": [
                {
                    "name": "germany",
                    "price": "344"
                },
                {
                    "name": "italy",
                    "price": "99"
                }
            ]
        }
    ]
}

Solution

  • Nest a predicate within a predicate. The inner one selects countries that have price = "12" and the outer one selects the fruits with one or more countries that match that price.

    fruits[countries[price="12"]].name

    See https://try.jsonata.org/oGXY13U98