问题描述
我正在与Jayway JsonPath库一起从我的phoneNumbers
类型为'iPhone'的JSON下面获取正确的'id'.
I am working with the Jayway JsonPath library to obtain the correct 'id' from below JSON where my phoneNumbers
type is 'iPhone'.
通常,我想知道在子JSON对象中指定了特定条件时如何从块的根元素中查找内容.
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.
我尝试了下面的表达式,分别选择了与iPhone类型关联的块以及ID列表,但是我无法进入属于JSON对象的根元素id
,其中我的手机类型为iPhone.有人可以指导我吗?对于这个问题,我需要将id
设置为1.
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.
要获取ID列表:$[*].id
要获取与iPhone类型相对应的json对象:$[*].phoneNumbers[?(@.type=='iPhone')]
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.
首先,在电话号码列表中找到具有iPhone的对象.然后只需选择ID.
First, find the objects that have an iPhone in the phone numbers list. Then just select the IDs.
尝试$[?(@.phoneNumbers[*].type=="iPhone")].id
.
修改
看起来 Java JsonPath 库(我认为您正在使用此库)支持许多功能.它没有列出contains()
,但是您可以尝试使用anyof
运算符:
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.
这篇关于根据子元素条件使用jsonpath获取根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!