Converting string to ordered dictionary?

后端 未结 3 2001
南笙
南笙 2020-12-19 13:29

I have a string which basically contains a bunch of JSON formatted text that I\'d ultimately like to export to Excel in \"pretty print\" format with the proper indentations

3条回答
  •  再見小時候
    2020-12-19 14:19

    First, you should consider using json (or even ast.literal_eval) instead of eval.

    Secondly, this won't work because the minute you turn it into a regular dictionary, all order is lost. You'll need to parse the "json" yourself if you want to put the information into an OrderedDict.

    Fortunately, this isn't quite as hard as you might think if you use the ast module. Here I'm assuming that the dictionary only contains strings but it shouldn't be too hard to modify for other purposes.

    s = '{"id":"0","last_modified":"undefined"}'
    import ast
    from collections import OrderedDict
    class DictParser(ast.NodeVisitor):
        def visit_Dict(self,node):
            keys,values = node.keys,node.values
            keys = [n.s for n in node.keys]
            values = [n.s for n in node.values]
            self.od = OrderedDict(zip(keys,values))
    
    dp = DictParser()
    dp.visit(ast.parse(s))
    ordered_dict = dp.od
    print ordered_dict
    

提交回复
热议问题