How to completely traverse a complex dictionary of unknown depth?

后端 未结 7 1975
深忆病人
深忆病人 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条回答
  •  囚心锁ツ
    2020-11-30 18:28

    If you know the meaning of the data, you might want to create a parse function to turn the nested containers into a tree of objects of custom types. You'd then use methods of those custom objects to do whatever you need to do with the data.

    For your example data structure, you might create Program, VariableDeclaration, VariableDeclarator, Identifier, Literal and BinaryExpression classes, then use something like this for your parser:

    def parse(d):
        t = d[u"type"]
    
        if t == u"Program":
            body = [parse(block) for block in d[u"body"]]
            return Program(body)
    
        else if t == u"VariableDeclaration":
            kind = d[u"kind"]
            declarations = [parse(declaration) for declaration in d[u"declarations"]]
            return VariableDeclaration(kind, declarations)
    
        else if t == u"VariableDeclarator":
            id = parse(d[u"id"])
            init = parse(d[u"init"])
            return VariableDeclarator(id, init)
    
        else if t == u"Identifier":
            return Identifier(d[u"name"])
    
        else if t == u"Literal":
            return Literal(d[u"value"])
    
        else if t == u"BinaryExpression":
            operator = d[u"operator"]
            left = parse(d[u"left"])
            right = parse(d[u"right"])
            return BinaryExpression(operator, left, right)
    
        else:
            raise ValueError("Invalid data structure.")
    

提交回复
热议问题