将字符串转换为有序字典? [英] Converting string to ordered dictionary?

查看:150
本文介绍了将字符串转换为有序字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它基本上包含一堆JSON格式的文本,我最终想以漂亮的打印格式导出到Excel,并且具有适当的嵌套缩进等。



为了可读性,保留键/值的原始顺序是必须的。我想要完成我想要的过程是



a)使用类似eval的方法将字符串转换为字典和
b)从集合库中使用OrderedDict保持订单不变。



但是我没有得到预期的结果:

 在[21]中:json_string = str({id:0,last_modified:undefined})
在[22]中:OrderedDict(eval(json_string))
Out [23]:OrderedDict([('last_modified','undefined'),('id','0')])

我还没有弄清楚我将如何以漂亮的打印格式将输出写入excel,但我希望这将是比较容易的部分! / p>

解决方案

您可以使用 object_pairs_hook 参数 JSONDecoder 将解码的字典更改为OrderedDict:

  import collection 
import json

decoder = json.JSONDecoder(object_pairs_hook = collections.OrderedDict)

json_string ='{id:0,
打印解码器(json_string)
json_string ='{last_modified:undefined,id:0}'
打印解码器.decode(json_string)

打印:

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


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 nesting, etc.

It's imperative that the original order of key/values is retained for readability purposes. My thought process to accomplish what I want is to

a) use something like eval to convert the string to a dictionary and b) use OrderedDict from the collections library to keep the order intact.

However I'm not getting 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 also haven't quite figured out yet how I'm going to write the output to excel in pretty print format, but I'd hope that'd be the comparatively easy part!

解决方案

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

这篇关于将字符串转换为有序字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆