In Python, using jsonpath-rw to get values ​​for a specific attribute (json / dict)

Here is my json:

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

I am trying to get the value for id , where description is "Test 1".

I found the following example on a 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?

+5
source share
1 answer

It seems that jsonpath-rw does not 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 exactly match the JsonPath syntax, but it is very similar, at least from the surface poll. Documentation is also available.

Of course, if your JSON is always in the same form (i.e. you don't have to deal with missing child objects, etc.), you can easily execute the same request using list comprehension or whatever something like that.

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

All Articles