Converting string to ordered dictionary?

后端 未结 3 2010
南笙
南笙 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: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')])
    

提交回复
热议问题