![](/img/trans.png)
[英]Python JSONPath Filter expressions error, Unexpected character for jsonpath-rw 1.4.0
[英]In Python, using jsonpath-rw to get values for specific attribute (json/dict)
這是我的json:
{
'test': [
{ "id": "1", "description": "Test 1" },
{ "id": "2", "description": "Test 2" }
]
}
我正在嘗試獲取id的值,其中描述為“Test 1”。
我在JsonPath頁面上找到了以下示例:
$..book[?(@.price<10)]
嘗試解析以下jsonxpath表達式時:
parse('$..test[?(@.description="Test 1")].id')
我收到以下錯誤:
jsonpath_rw.lexer.JsonPathLexerError: Error on line 1, col 7: Unexpected character: ?
我究竟做錯了什么? 或者,有更好的方法嗎?
似乎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語法,但它非常相似,至少從敷衍調查來看。 文檔也可用。
當然,如果您的JSON將始終采用相同的形式(即您不必處理丟失的子對象等),那么您可以使用列表推導或類似的東西輕松地執行相同的查詢。
json = { ... }
ids = [t['id'] for t in json['test'] if t['description'] == 'Test 1']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.