Can I get JSON to load into an OrderedDict?(我可以让 JSON 加载到 OrderedDict 中吗?)
问题描述
好的,我可以在 json.dump 中使用 OrderedDict.也就是说,OrderedDict 可以用作 JSON 的输入.
Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.
但它可以用作输出吗?如果有怎么办?就我而言,我想 load 到 OrderedDict 中,这样我就可以保持文件中键的顺序.
But can it be used as an output? If so how? In my case I'd like to load into an OrderedDict so I can keep the order of the keys in the file.
如果没有,是否有某种解决方法?
If not, is there some kind of workaround?
推荐答案
是的,你可以.通过为 JSONDecoderobject_pairs_hook 参数>.事实上,这就是文档中给出的确切示例.
Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation.
>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>>
您可以将此参数传递给 json.loads(如果您不需要解码器实例用于其他目的),如下所示:
You can pass this parameter to json.loads (if you don't need a Decoder instance for other purposes) like so:
>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
"foo": 1,
"bar": 2
}
>>>
使用 json.load 以同样的方式完成:
Using json.load is done in the same way:
>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
这篇关于我可以让 JSON 加载到 OrderedDict 中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以让 JSON 加载到 OrderedDict 中吗?
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
