How to completely traverse a complex dictionary of unknown depth?

后端 未结 7 1955
深忆病人
深忆病人 2020-11-30 17:35

Importing from JSON can get very complex and nested structures. For example:

{u\'body\': [{u\'declarations\': [{u\'id\': {u\'name\': u\'i\',
            


        
7条回答
  •  -上瘾入骨i
    2020-11-30 18:21

    If you only need to walk the dictionary, I'd suggest using a recursive walk function that takes a dictionary and then recursively walks through its elements. Something like this:

    def walk(node):
        for key, item in node.items():
            if item is a collection:
                walk(item)
            else:
                It is a leaf, do your thing
    

    If you also want to search for elements, or query several elements that pass certain criteria, have a look at the jsonpath module.

提交回复
热议问题