json.loads()不保持顺序 [英] json.loads() doesn't keep order

查看:92
本文介绍了json.loads()不保持顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将我的String设置为类似于JSON的格式,因此可以在其上执行json.loads.当我在屏幕上打印时,结果发现它弄乱了顺序.我知道Python字典不排序,但是有什么方法可以保持此顺序?我真的需要保留它.谢谢!

I have formatted my String to look like JSON so I could do json.loads on it. When I printed on the screen it turned out it messed up the order. I know that Python dictonaries are not ordered but is there ANY way to keeps this order? I really need to keep it. Thanks!

推荐答案

这两个JSON en Python字典(这些都是JSON对象)都是无序的.因此,实际上这样做没有任何意义,因为JSON编码器可以更改顺序.

Both JSON en Python dictionaries (those are JSON objects) are unordered. So in fact it does not makes any sense to do that, because the JSON encoder can change the order.

但是,您可以定义一个自定义JSON解码器,然后使用该解码器对其进行解析.因此,这里的字典钩子将是OrderedDict:

You can however define a custom JSON decoder, and then parse it with that decoder. So here the dictionary hook willl be an OrderedDict:

from json import JSONDecoder
from collections import OrderedDict

customdecoder = JSONDecoder(object_pairs_hook=OrderedDict)

然后您可以使用以下代码进行解码:

Then you can decode with:

customdecoder.decode(your_json_string)

因此,这会将项目存储在OrderedDict中,而不是字典中.但是请注意-如前所述-JSON对象的键的顺序未指定.

This will thus store the items in an OrderedDict instead of a dictionary. But be aware - as said before - that the order of the keys of JSON objects is unspecified.

或者,您也可以将钩子传递给loads函数:

Alternatively, you can also pass the hook to the loads function:

from json import loads
from collections import OrderedDict

loads(your_json_string, object_pairs_hook=OrderedDict)

更新:自 ,标准json.loadjson.loads应该可以正常工作.但是请注意,JSON对象仍然是无序的,因此JavaScript端可以按任何顺序加载/转储该对象.

Update: as of python-3.7, a dictionary retains insertion order. So if one uses python-3.7, the standard json.load and json.loads should work fine. Note however that a JSON object is still unordered, so that the JavaScript end can load/dump the object in any order.

这篇关于json.loads()不保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆