【问题标题】:In Python, using jsonpath-rw to get values for specific attribute (json/dict)在 Python 中,使用 jsonpath-rw 获取特定属性(json/dict)的值
【发布时间】:2015-05-24 01:03:04
【问题描述】:

这是我的 json:

{
   'test': [
        { "id": "1", "description": "Test 1" },
        { "id": "2", "description": "Test 2" }
    ]
}

我正在尝试获取 id 的值,其中 description 是“测试 1”。

我在 JsonPath 页面上找到了以下示例:

$..book[?(@.price<10)]

尝试解析以下 jsonxpath 表达式时:

parse('$..test[?(@.description="Test 1")].id')

我收到以下错误:

jsonpath_rw.lexer.JsonPathLexerError: Error on line 1, col 7: Unexpected character: ?

我做错了什么?或者,有没有更好的方法来做到这一点?

【问题讨论】:

  • 奇怪的是,看看lexer code,jsonpath-rw 似乎根本不支持?(boolean) 过滤机制。

标签: python jsonpath


【解决方案1】:

jsonpath-rw 似乎不支持此功能。也许考虑另一个图书馆? ObjectPath 看起来很有希望:

>>> import objectpath
>>> json_obj = { ... } # This has to be pre-parsed
>>> tree = objectpath.Tree(json_obj)
>>> ids = tree.execute('$..test[@.description is "Test 1"].id')
>>> print list(ids)
["1"]

它并不完全遵循 JsonPath 语法,但它非常相似,至少从一个敷衍的调查来看。 Documentation 也可以。

当然,如果您的 JSON 始终采用相同的形式(即您不必处理丢失的子对象等),那么您可以使用列表推导或类似的方法轻松地执行相同的查询。

json = { ... }
ids = [t['id'] for t in json['test'] if t['description'] == 'Test 1']

【讨论】:

  • 请记住.. 运算符(递归下降/深度搜索)非常慢。如果您确定测试位于文档的根目录中且仅位于文档的根目录中,请使用 .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多