本文介绍了我可以将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?

推荐答案

是的,可以.通过为 JSONDecoder 指定object_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(如果不需要其他用途的Decoder实例),如下所示:

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的方式相同:

>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)

这篇关于我可以将JSON加载到OrderedDict吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:36