halloleo
halloleo

Reputation: 10454

Xpath-like package for Python to find keys on all level in lists and dicts

Given is a data structure which has the key TEXT in arbitrary positions in the structure like this example:

{'info': [
    {'TEXT': 'SUBINLIST'},
          {'duda': {
              'TEXT': 'SUBSUB',
              'walter': 'jaja'}}
          {'hey': [
              {'jess': 'morning'},
              {'TEXT': 'DEEPEST'}
          ]}  
    ],
 'TEXT': 'TOPLEVEL'}

I want to find the values of the TEXT keys. Is there a XPath-like package for Python where I can define an appropriate path expression so that I get for the example the following result returned:

['SUBINLIST', 'SUBSUB', 'DEEPEST', 'TOPLEVEL']

Note: I do not want to find the keys through a recursive Python function, but via an call to a package/library/module (which obviously will do that internally as well).

I tried jsonpath-rw, but could not come up with an expression which finds the values in arbitrarily nested dicts and lists.

Upvotes: 1

Views: 794

Answers (1)

Andersson
Andersson

Reputation: 52675

You can try jsonpath as below:

import jsonpath

my_dict = {'info': [{'TEXT': 'SUBINLIST'},{'duda': {'TEXT': 'SUBSUB','walter': 'jaja'}}, {'hey': [{'jess': 'morning'}, {'TEXT': DEEPEST'}]}], 'TEXT': 'TOPLEVEL'}
print(jsonpath.jsonpath(my_dict, "$..TEXT"))

Output:

['TOPLEVEL', 'SUBINLIST', 'SUBSUB', 'DEEPEST']

Upvotes: 2

Related Questions