Search code examples
pythonjsonpath

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


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?


Solution

  • 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']