Convert string to ordered dictionary?

I have a line that basically contains a bunch of JSON formatted text, which I would ultimately want to export to Excel in a "pretty printable" format with corresponding recesses for nesting, etc.

It is imperative that the original key / value order is maintained for readability purposes. My thought process to achieve what I want is

a) use something like eval to convert a string to a dictionary; and b) use the OrderedDict from the collection library to keep order in circulation.

However, I do not get the 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 still do not quite understand how I am going to write the conclusion in order to succeed in a fairly printed format, but I hope this will be a relatively simple part!

+4
source share
3 answers

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) 

Fingerprints:

 OrderedDict([(u'id', u'0'), (u'last_modified', u'undefined')]) OrderedDict([(u'last_modified', u'undefined'), (u'id', u'0')]) 
+15
source

First you must use json (or even ast.literal_eval ) instead of eval .

Secondly, this will not work, because as soon as you turn it into a regular dictionary, the whole order will be lost. You will need to parse "json" yourself if you want to put the information in an OrderedDict.

Fortunately, this is not as difficult as you think if you use the ast module. Here I assume that the dictionary contains only strings, but it should not be too difficult 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 = [ns for n in node.keys] values = [ns 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 
+5
source

This message is about converting a string to orderdict with string manipulation:

fooobar.com/questions/1481679 / ...

0
source

Source: https://habr.com/ru/post/1481677/


All Articles