如何通过JSONPath提取type为'in'对应的id值?
解决Jayway JSONPath关联提取对应id的问题
原始JSON结构
{ "a": [ { "b": { "c": [ { "id": "123" } ], "d": { "e": { "f": [ { "name": "abc", "type": "in" }, { "name": "xyz", "type": "out" ] } } } }, { "b": { "c": [ { "id": "456" } ], "d": { "e": { "f": [ { "name": "def", "type": "out" }, { "name": "pqr", "type": "out" ] } } } ] }
需求说明
提取所有type字段值等于'in'的对应id值,示例中仅第一个元素存在type='in',预期输出为123。
问题场景
- 已通过表达式
$.a[*].b.d[*].f[?(@.type=='in')]定位到type为'in'的节点,但无法关联提取对应的id。 - 尝试转换为Jayway JSONPath表达式
$.a[?(@.b.d.e.f[?(@.type=='in')])].b.c[*].id时,出现语法错误:Unexpected token '?': _$_v.b.d.e.f[?(_$_v.type=='in'
正确的Jayway JSONPath表达式
Jayway不支持嵌套的[?()]过滤语法,需使用any()函数判断数组中是否存在符合条件的元素,正确表达式如下:
$.a[?(@.b.d.e.f.any(it.type == 'in'))].b.c[*].id
说明
@.b.d.e.f.any(it.type == 'in'):判断当前a数组元素的b.d.e.f数组中,是否存在type等于'in'的元素。- 过滤出符合条件的
a元素后,提取其b.c数组下所有的id值。若c数组固定只有一个元素,也可写成$.a[?(@.b.d.e.f.any(it.type == 'in'))].b.c[0].id。
内容的提问来源于stack exchange,提问作者pavan kumar
相关产品推荐
相关产品推荐

