简体   繁体   中英

Get root element using jsonpath based on sub elements condition

I am working with the Jayway JsonPath library to obtain the correct 'id' from below JSON where my phoneNumbers type is 'iPhone'.

In general, I would like to know how to find something from the root element of a block when a specific condition is specified in the sub-JSON objects.

I tried below expressions that select the block associated with iPhone type and also a list of ids respectively, but I am not able to get to the root element id belonging to the JSON object where my phone type is iPhone. Can someone please guide me? I need to get the id as 1 for this question.

To get the list of ids: $[*].id

To get the json object corresponding to iPhone type: $[*].phoneNumbers[?(@.type=='iPhone')]

[
    {
        "id": "1",
        "phoneNumbers": [
            {
                "type": "iPhone",
                "number": "0123-4567-8888"
            },
            {
                "type": "home",
                "number": "0123-4567-8910"
            }
        ]
    },
    {
        "id": "2",
        "phoneNumbers": [
            {
                "type": "x",
                "number": "0123-4567-8888"
            },
            {
                "type": "y",
                "number": "0123-4567-8910"
            }
        ]
    }
]

I think you want your expression to look deeper.

First, find the objects that have an iPhone in the phone numbers list. Then just select the IDs.

Try $[?(@.phoneNumbers[*].type=="iPhone")].id .


Edit

It looks like the Java JsonPath library (I think you're using this) supports a number of functions. It doesn't list a contains() , but you might try the anyof operator:

$[?(@.phoneNumbers[*].type anyof ["iPhone"])].id

Note that this is definitely implementation-specific and will likely not work with any other library.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM