问题
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