且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以将 JSON 加载到 OrderedDict 中吗?

更新时间:2022-10-17 23:19:31

是的,你可以.通过将 object_pairs_hook 参数指定给 JSONDecoder.事实上,这是文档中给出的确切示例.

>>>json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')OrderedDict([('foo', 1), ('bar', 2)])>>>

您可以将此参数传递给 json.loads(如果您不需要 Decoder 实例用于其他目的),如下所示:

>>>导入json>>>从集合导入 OrderedDict>>>数据 = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)>>>打印 json.dumps(data, indent=4){富":1,酒吧":2}>>>

使用 json.load 的方式相同:

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

Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.

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?

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

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
}
>>> 

Using json.load is done in the same way:

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