python - 将字符串转换为有序字典?

标签 python python-2.7 dictionary

我有一个字符串,它基本上包含一堆 JSON 格式的文本,我最终想以“ pretty-print ”格式导出到 Excel,并带有适当的嵌套缩进等。

为了便于阅读,必须保留键/值的原始顺序。我完成我想要的事情的思维过程是

a) 使用 eval 之类的东西将字符串转换为字典,然后 b) 使用集合库中的 OrderedDict 来保持订单的完整性。

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

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

我还没有完全弄清楚如何以 pretty-print 格式将输出写入 excel,但我希望这是相对容易的部分!

最佳答案

您可以将 object_pairs_hook 参数用于 JSONDecoder将解码后的字典更改为 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)

这打印:

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

关于python - 将字符串转换为有序字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641110/

相关文章:

python - 如何动态代理类的方法?

python - 为什么在更新字典时得到 None?

python - 迭代 python 数组并找到 50 个值的平均值/最小值/最大值

python - 如何在 Python 中对模块级对象进行更改? (如 Pylons 元对象)

Python gekko 找不到 "options.json"文件

python - 从 python 中的一行中拉出特定的子字符串

python - pygtk 和 multiprocessing - 从另一个运行无限循环的进程不断更新 textview

Python:为控制台打印编写单元测试

python - 从嵌套字典中删除某些字段?

c# - 无法访问的代码和验证