【问题标题】:Checking for an element in an array with jsonpath_ng fails with JsonPathParseError使用 jsonpath_ng 检查数组中的元素失败并出现 JsonPathParseError
【发布时间】: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

【问题讨论】:

标签: python json jsonpath json-path-expression jsonpath-ng


【解决方案1】:
jpexpr = parse('$[?(@..test[?(@ == "a2")].`len` > 0)]')

为我完成了这项工作......

from jsonpath_ng.ext import parse

a = [{"id": "a", "test": ["a1", "a2"]}, {"id": "b", "test": ["a1", "a3"]}]

jpexpr = parse('$[?(@..test[?(@ == "a2")].`len` > 0)]')

for i in jpexpr.find(a):
    print(i.value)

导致

{'id': 'a', 'test': ['a1', 'a2']}

正是我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2012-09-02
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多