Search code examples
pythonxpathjmespathjson-path-expression

XPath like query for nested python dictionaries


Is there a way to define a XPath type query for nested python dictionaries.

Something like this:

foo = {
  'spam':'eggs',
  'morefoo': {
               'bar':'soap',
               'morebar': {'bacon' : 'foobar'}
              }
   }

print( foo.select("/morefoo/morebar") )

>> {'bacon' : 'foobar'}

I also needed to select nested lists ;)

This can be done easily with @jellybean's solution:

def xpath_get(mydict, path):
    elem = mydict
    try:
        for x in path.strip("/").split("/"):
            try:
                x = int(x)
                elem = elem[x]
            except ValueError:
                elem = elem.get(x)
    except:
        pass

    return elem

foo = {
  'spam':'eggs',
  'morefoo': [{
               'bar':'soap',
               'morebar': {
                           'bacon' : {
                                       'bla':'balbla'
                                     }
                           }
              },
              'bla'
              ]
   }

print xpath_get(foo, "/morefoo/0/morebar/bacon")

[EDIT 2016] This question and the accepted answer are ancient. The newer answers may do the job better than the original answer. However I did not test them so I won't change the accepted answer.


Solution

  • Not exactly beautiful, but you might use sth like

    def xpath_get(mydict, path):
        elem = mydict
        try:
            for x in path.strip("/").split("/"):
                elem = elem.get(x)
        except:
            pass
    
        return elem
    

    This doesn't support xpath stuff like indices, of course ... not to mention the / key trap unutbu indicated.