Converting string to ordered dictionary?

后端 未结 3 1984
南笙
南笙 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:08

    This post is related to string to ordereddict conversion with string manipulation:

    https://stackoverflow.com/a/27177986/1128709

    0 讨论(0)
  • 2020-12-19 14:17

    You can use the object_pairs_hook argument to JSONDecoder to change the decoded dictionaries to OrderedDict:

    import collections
    import json
    
    decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
    
    json_string = '{"id":"0","last_modified":"undefined"}'
    print decoder.decode(json_string)
    json_string = '{"last_modified":"undefined","id":"0"}'
    print decoder.decode(json_string)
    

    This prints:

    OrderedDict([(u'id', u'0'), (u'last_modified', u'undefined')])
    OrderedDict([(u'last_modified', u'undefined'), (u'id', u'0')])
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题