python - Converting string to ordered dictionary? -
i have string contains bunch of json formatted text i'd export excel in "pretty print" format proper indentations nesting, etc.
it's imperative original order of key/values retained readability purposes. thought process accomplish want
a) use eval convert string dictionary , b) use ordereddict collections library keep order intact.
however i'm not getting expected result:
in [21]: json_string = str({"id":"0","last_modified":"undefined"}) in [22]: ordereddict(eval(json_string)) out[23]: ordereddict([('last_modified', 'undefined'), ('id', '0')]) i haven't quite figured out yet how i'm going write output excel in pretty print format, i'd hope that'd comparatively easy part!
you can use object_pairs_hook argument jsondecoder change decoded dictionaries 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')])
Comments
Post a Comment