Xpath like query for nested python dictionaries

后端 未结 10 1673
情话喂你
情话喂你 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:14

    dict > jmespath

    You can use JMESPath which is a query language for JSON, and which has a python implementation.

    import jmespath # pip install jmespath
    
    data = {'root': {'section': {'item1': 'value1', 'item2': 'value2'}}}
    
    jmespath.search('root.section.item2', data)
    Out[42]: 'value2'
    

    The jmespath query syntax and live examples: http://jmespath.org/tutorial.html

    dict > xml > xpath

    Another option would be converting your dictionaries to XML using something like dicttoxml and then use regular XPath expressions e.g. via lxml or whatever other library you prefer.

    from dicttoxml import dicttoxml  # pip install dicttoxml
    from lxml import etree  # pip install lxml
    
    data = {'root': {'section': {'item1': 'value1', 'item2': 'value2'}}}
    xml_data = dicttoxml(data, attr_type=False)
    Out[43]: b'
    value1value2
    ' tree = etree.fromstring(xml_data) tree.xpath('//item2/text()') Out[44]: ['value2']

    Json Pointer

    Yet another option is Json Pointer which is an IETF spec that has a python implementation:

    • https://github.com/stefankoegl/python-json-pointer

    From the jsonpointer-python tutorial:

    from jsonpointer import resolve_pointer
    
    obj = {"foo": {"anArray": [ {"prop": 44}], "another prop": {"baz": "A string" }}}
    
    resolve_pointer(obj, '') == obj
    # True
    
    resolve_pointer(obj, '/foo/another%20prop/baz') == obj['foo']['another prop']['baz']
    # True
    
    >>> resolve_pointer(obj, '/foo/anArray/0') == obj['foo']['anArray'][0]
    # True
    
    

提交回复
热议问题