Here's my json:
{
'test': [
{ "id": "1", "description": "Test 1" },
{ "id": "2", "description": "Test 2" }
]
}
I'm trying to get the value for id where description is "Test 1".
I found the following example on the JsonPath page:
$..book[?(@.price<10)]
When trying to parse the following jsonxpath expression:
parse('$..test[?(@.description="Test 1")].id')
I get the following error:
jsonpath_rw.lexer.JsonPathLexerError: Error on line 1, col 7: Unexpected character: ?
What am I doing wrong? Alternatively, is there a better way to do this?
It appears that jsonpath-rw
doesn't support this feature. Perhaps consider another library? ObjectPath
looks promising:
>>> 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"]
It doesn't quite follow the JsonPath syntax exactly, but it's quite similar, at least from a perfunctory survey. Documentation is also available.
Of course, if your JSON will always be in the same form (i.e. you won't have to deal with missing child objects, etc), then you could easily do the same query using a list comprehension, or something similar.
json = { ... }
ids = [t['id'] for t in json['test'] if t['description'] == 'Test 1']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With