How can I select deeply nested key:values from dictionary in python

后端 未结 2 1098
执笔经年
执笔经年 2020-12-19 21:00

I have downloaded a json data from a website, and I want to select specific key:values from a nested json. I converted the json to python dictionary. Then I used dictionary

2条回答
  •  星月不相逢
    2020-12-19 21:26

    I suggest you to use python-benedict, a solid python dict subclass with full keypath support and many utility methods.

    It provides IO support with many formats, including json.

    You can initialize it directly from the json file:

    from benedict import benedict
    
    d = benedict.from_json('data.json')
    

    Now your dict has keypath support:

    print(d['payload.metadata.coverImage.id'])
    
    # or use get to avoid a possible KeyError
    print(d.get('payload.metadata.coverImage.id'))
    

    Installation: pip install python-benedict

    Here the library repository and the documentation: https://github.com/fabiocaccamo/python-benedict

    Note: I am the author of this project

提交回复
热议问题