Get root element using jsonpath based on sub elements condition

六眼飞鱼酱① 提交于 2020-12-14 11:42:51

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/63470519/get-root-element-using-jsonpath-based-on-sub-elements-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!