我可以将JSON加载到OrderedDict吗?

本文翻译自:Can I get JSON to load into an OrderedDict?

Ok so I can use an OrderedDict in json.dump . 好的,所以我可以在json.dump使用OrderedDict。 That is, an OrderedDict can be used as an input to JSON. 也就是说,可以将OrderedDict用作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. 就我而言,我想load到OrderedDict中,以便可以将键的顺序保留在文件中。

If not, is there some kind of workaround? 如果没有,是否有某种解决方法?


#1楼

参考:https://stackoom.com/question/T2eJ/我可以将JSON加载到OrderedDict吗


#2楼

In addition to dumping the ordered list of keys alongside the dictionary, another low-tech solution, which has the advantage of being explicit, is to dump the (ordered) list of key-value pairs ordered_dict.items() ; 除了在字典旁边转储键的有序列表之外,另一种具有显式优点的低技术解决方案是转储键值对的(有序)列表ordered_dict.items() loading is a simple OrderedDict(<list of key-value pairs>) . 加载是一个简单的OrderedDict(<list of key-value pairs>) This handles an ordered dictionary despite the fact that JSON does not have this concept (JSON dictionaries have no order). 尽管JSON没有这个概念(JSON字典没有顺序),但这仍然可以处理有序字典。

It is indeed nice to take advantage of the fact that json dumps the OrderedDict in the correct order. 利用json以正确的顺序转储OrderedDict的事实确实很好。 However, it is in general unnecessarily heavy and not necessarily meaningful to have to read all JSON dictionaries as an OrderedDict (through the object_pairs_hook argument), so an explicit conversion of only the dictionaries that must be ordered makes sense too. 但是,通常必须将所有 JSON词典读取为OrderedDict(通过object_pairs_hook参数)是不必要的object_pairs_hook ,因此不一定有意义,因此显式转换必须排序的词典也是有意义的。


#3楼

The normally used load command will work if you specify the object_pairs_hook parameter: 如果指定object_pairs_hook参数,则通常使用的load命令将起作用:

import json
from  collections import OrderedDict
with open('foo.json', 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)

#4楼

Some great news! 一些好消息! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries ( https://mail.python.org/pipermail/python-dev/2016-September/146327.html ). 从3.6版开始,cPython实现保留了字典的插入顺序( https://mail.python.org/pipermail/python-dev/2016-September/146327.html )。 This means that the json library is now order preserving by default. 这意味着json库现在默认保留顺序。 Observe the difference in behaviour between python 3.5 and 3.6. 观察python 3.5和3.6之间的行为差​​异。 The code: 编码:

import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))

In py3.5 the resulting order is undefined: 在py3.5中,结果顺序是不确定的:

{
    "fiddle": {
        "bar": 2,
        "foo": 1
    },
    "bar": 2,
    "foo": 1
}

In the cPython implementation of python 3.6: 在python 3.6的cPython实现中:

{
    "foo": 1,
    "bar": 2,
    "fiddle": {
        "bar": 2,
        "foo": 1
    }
}

The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html 真正的好消息是,这已成为python 3.7的语言规范(与cPython 3.6+的实现细节相反): https ://mail.python.org/pipermail/python-dev/2017-December/151283 .html

So the answer to your question now becomes: upgrade to python 3.6! 因此,您的问题的答案现在变成:升级到python 3.6! :) :)


#5楼

除了转储字典,您总是可以写出键列表,然后通过遍历列表来重建OrderedDict


#6楼

Yes, you can. 是的你可以。 By specifying the object_pairs_hook argument to JSONDecoder . 通过为JSONDecoder指定object_pairs_hook参数。 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: 您可以将此参数传递给json.loads (如果不需要出于其他目的的Decoder实例),如下所示:

>>> 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: 使用json.load的方式相同:

>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值