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

如何用Jayway JsonPath基于另一对象字段提取对象属性子集?

问题:使用Jayway JsonPath按指定属性过滤对象

给定两个JSON对象:

  • toBeFiltered:待过滤的对象,包含多个属性
  • includeFields:指定需要保留的属性,其键名即为需保留的属性名

示例输入JSON:

{
  "toBeFiltered": {
    "a": "AAA",    
    "b": "BBB",    // 因includeFields不含"b",将被排除
    "c": "CCC"     
  },
  "includeFields": {
    "a": true,
    "c": true 
  } 
}

需求:通过JsonPath表达式筛选出toBeFiltered中存在于includeFields的属性,得到结果:

{
  "a": "AAA",
  "c": "CCC"
}

请问是否可通过Jayway JsonPath实现该需求?若可行,对应的表达式是什么?


回答

可以实现,对应的Jayway JsonPath表达式如下:

$..toBeFiltered.*[?(@property in $..includeFields.keySet())]

表达式说明:

  • $..toBeFiltered.*:遍历toBeFiltered下的所有属性值
  • [?(@property in $..includeFields.keySet())]:筛选出属性名(@property)存在于includeFields键集合中的项
  • Jayway JsonPath支持@property获取当前节点的属性名,同时支持调用keySet()方法获取对象的所有键名,结合in操作符完成匹配判断

注意:该表达式依赖Jayway JsonPath的扩展特性,标准JsonPath规范未包含@property和keySet()这类语法,仅Jayway实现支持。

内容的提问来源于stack exchange,提问作者Niklas Eldberger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:54:58