【发布时间】:2022-01-21 23:36:38
【问题描述】:
我正在尝试使用 Python 中的 jsonpath_ng 过滤我的 JSON 数据中包含特定值的元素。数据看起来像
[
{
"id": "a",
"test": [
"a1",
"a2"
]
},
{
"id": "b",
"test": [
"a1",
"a3"
]
}
]
使用查询 $[?(@.test contains "a2")] 或 $[?("a2" in @.test)] 在 PyCharm 中测试数据工作正常并返回预期结果
[
{
"id": "a",
"test": [
"a1",
"a2"
]
}
]
不幸的是,在 Python 中使用 jsonpath_ng 尝试此操作会导致错误...
from jsonpath_ng.ext import parse
a = [{"id": "a", "test": ["a1", "a2"]}, {"id": "b", "test": ["a1", "a3"]}]
jpexpr = parse('$[?(@.test contains "a2")]')
导致错误jsonpath_ng.exceptions.JsonPathParserError: Parse error at 1:11 near token contains (ID)。使用jpexpr = parse('$[?("a2" in @.test)]') 显示了与jsonpath_ng.exceptions.JsonPathParserError: Parse error at 1:9 near token in (ID) 类似的行为
无论是搜索 Google 还是 SO,如果 jsonpath_ng 存在限制,我都无法找到答案是否我做错了。
jsonpath_ng 中是否不支持此过滤器?如果是这种情况,是否有人有解决方法的好主意?
感谢大家的帮助, .kai
【问题讨论】:
-
好的,发现有用的数组运算符根本不是“官方”JSON 路径规范的一部分。仍然会感谢建议的解决方法。
标签: python json jsonpath json-path-expression jsonpath-ng