Skip to content Skip to sidebar Skip to footer

Converting String To Ordered Dictionary?

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 for nestin

Solution 1:

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')])

Solution 2:

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
classDictParser(ast.NodeVisitor):
    defvisit_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

Solution 3:

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

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

Post a Comment for "Converting String To Ordered Dictionary?"