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

如何使用Python jsonpath_ng筛选嵌套数据:获取符合条件的完整字典

解决方法

你需要调整JSONPath表达式,将筛选条件定位到数组的整个元素上,而不是仅针对attrs字段。

原表达式$.[*].attrs[?value > 200]是在attrs子对象中筛选,所以只会返回符合条件的attrs内容。修改后的表达式需要匹配数组中满足attrs.value > 200的完整对象:

import json
from jsonpath_ng.ext import parse

json_str = '''[
{
  "uid": {"type": "t1", "id": "hello"},
  "attrs": {
    "value": 123
  }
},
{
  "uid": {"type": "t2", "id": "world"},
  "attrs": {
    "value": 456
  }
}
]
'''
json_obj = json.loads(json_str)
# 修改后的JSONPath表达式
result = [match.value for match in parse('$.[*][?attrs.value > 200]').find(json_obj)]
print(result)

运行后会输出你期望的结果:

[{"uid": {"type": "t2", "id": "world"}, "attrs": {"value": 456}}]

关键说明

  • $.[*]遍历数组中的每个对象
  • [?attrs.value > 200]作为筛选条件,判断当前对象的attrs.value是否大于200,满足条件则返回整个对象

内容的提问来源于stack exchange,提问作者Relax ZeroC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:43:11