Xpath like query for nested python dictionaries

后端 未结 10 1656
情话喂你
情话喂你 2020-12-02 15:45

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

Something like this:

foo = {
  \'spam\':\'eggs\',
  \'morefoo\': {
               


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 16:09

    There is the newer jsonpath-rw library supporting a JSONPATH syntax but for python dictionaries and arrays, as you wished.

    So your 1st example becomes:

    from jsonpath_rw import parse
    
    print( parse('$.morefoo.morebar').find(foo) )
    

    And the 2nd:

    print( parse("$.morefoo[0].morebar.bacon").find(foo) )
    

    PS: An alternative simpler library also supporting dictionaries is python-json-pointer with a more XPath-like syntax.

提交回复
热议问题