This question already has an answer here:
这个问题在这里已有答案:
- Python json.loads changes the order of the object 2 answers
Python json.loads改变了对象2答案的顺序
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!
我已将我的String格式化为JSON,因此我可以对其执行json.loads。当我在屏幕上打印时,它结果搞砸了订单。我知道Python dictonaries没有订购,但有没有办法保持这个顺序?我真的需要保留它。谢谢!
1 个解决方案
#1
6
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和Python字典(那些是JSON对象)都是无序的。所以实际上这样做没有任何意义,因为JSON编码器可以改变顺序。
You can however define a custom JSON decoder, and then parse it with that decoder. So here the dictionary hook willl be an OrderedDict
:
但是,您可以定义自定义JSON解码器,然后使用该解码器解析它。所以这里的字典钩子将是一个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)
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.
因此,这将把项目存储在OrderedDict而不是字典中。但要注意 - 如前所述 - JSON对象的键的顺序是未指定的。
Alternatively, you can also pass the hook to the loads
function:
或者,您也可以将钩子传递给loads函数:
from json import loads
from collections import OrderedDict
loads(your_json_string, object_pairs_hook=OrderedDict)
#1
6
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和Python字典(那些是JSON对象)都是无序的。所以实际上这样做没有任何意义,因为JSON编码器可以改变顺序。
You can however define a custom JSON decoder, and then parse it with that decoder. So here the dictionary hook willl be an OrderedDict
:
但是,您可以定义自定义JSON解码器,然后使用该解码器解析它。所以这里的字典钩子将是一个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)
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.
因此,这将把项目存储在OrderedDict而不是字典中。但要注意 - 如前所述 - JSON对象的键的顺序是未指定的。
Alternatively, you can also pass the hook to the loads
function:
或者,您也可以将钩子传递给loads函数:
from json import loads
from collections import OrderedDict
loads(your_json_string, object_pairs_hook=OrderedDict)