You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

说明

  1. @.b.d.e.f.any(it.type == 'in'):判断当前a数组元素的b.d.e.f数组中,是否存在type等于'in'的元素。
  2. 过滤出符合条件的a元素后,提取其b.c数组下所有的id值。若c数组固定只有一个元素,也可写成$.a[?(@.b.d.e.f.any(it.type == 'in'))].b.c[0].id。

内容的提问来源于stack exchange,提问作者pavan kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:27:16