在jsonpath中进行过滤时,如何获取第一个元素? [英] How to get the first element when filter in jsonpath?
问题描述
所以我正在研究以下json:
So I'm working on the below json:
{
"id": "",
"owner": "some dude",
"metaData": {
"request": {
"ref": null,
"contacts":[
{
"email": null,
"name": null,
"contactType": "R"
},
{
"email": null,
"name": "Dante",
"contactType": "S"
}
]
}
}
}
我要检索的name
联系人的类型为S
,并且只有第一个返回的联系人.
I want to retrieve the name
of contact has type S
and only the first one that returned.
使用具有此路径"$..contacts[?(@.contactType == 'S')].name"
的jsonpath始终返回字符串数组,因为过滤操作始终将结果作为数组返回.
Using jsonpath with this path "$..contacts[?(@.contactType == 'S')].name"
always return an array of string because a filter operation always return result as an array.
所以我尝试了"$..contacts[?(@.contactType == 'S')].name[0]"
和"$..contacts[?(@.contactType == 'S')][0].name"
,但是没有运气.这些路径返回空结果.
So I tried "$..contacts[?(@.contactType == 'S')].name[0]"
and "$..contacts[?(@.contactType == 'S')][0].name"
but no luck. Those path returns empty results.
所以我的问题是,在jsonpath中使用filter时,是否有任何方法只能获取第一个元素.我目前正在使用jayway jsonpath v2.2.0.
So my question is, is there any way to get only first element when using filter in jsonpath. I'm currently using jayway jsonpath v2.2.0.
推荐答案
我发现最快的解决方案是将其与列表进行比较,因此在您的情况下是这样的:
The quickest solution I found was just comparing it with a list, so like this in your scenario:
.andExpect(jsonPath("$..contacts[?(@.contactType == 'S')].name", equalTo(Arrays.asList("Dante"))))
(假设您尝试在测试中比较某些结果)
(Assuming you are trying to compare some result in a test of course)
这篇关于在jsonpath中进行过滤时,如何获取第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!