简体   繁体   English

使用None作为键时json.dumps无法排序的类型

[英]json.dumps unorderable types when using None as a key

When calling json.dumps on an object that contains a dictionary with a None and str type, how do I have it sort the results without throwing an exception? 在包含包含Nonestr类型的字典的对象上调用json.dumps时,如何在不引发异常的情况下对结果进行排序? I'm trying it with sort_keys=True but that threw a TypeError . 我正在尝试使用sort_keys=True但这引发了TypeError I don't care how None and bar are sorted relative to each other as long as it's consistent from run-to-run. 我不关心Nonebar如何相对于彼此排序,只要它们在每次运行之间都保持一致即可。

import json
foo = {None: 7, 'bar': 8}
json.dumps(foo)

which prints 哪个打印

'{"bar": 8, "null": 7}'

But then 但是之后

json.dumps(foo, sort_keys=True)

prints 版画

 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "C:\Program Files\Python35\lib\json\__init__.py", line 237, in dumps
     **kw).encode(obj)
   File "C:\Program Files\Python35\lib\json\encoder.py", line 198, in encode
     chunks = self.iterencode(o, _one_shot=True)
   File "C:\Program Files\Python35\lib\json\encoder.py", line 256, in iterencode
     return _iterencode(o, 0)
 TypeError: unorderable types: NoneType() < str()

Turns out a key of null is invalid JSON. 原来, null的键是无效的JSON。 Clearly, json.dumps(...) converts None keys to the string 'null' before returning, but presumably json.dumps(..., sort_keys=True) does the sorting before the conversion to a string. 显然, json.dumps(...)在返回之前将None键转换为字符串'null' ,但是大概json.dumps(..., sort_keys=True)在转换为字符串之前进行了排序。

One solution I found that allowed both sorting and displaying the structure in JSON is to convert it to JSON first, then sort the keys, like so: 我发现允许在JSON中对结构进行排序和显示的一种解决方案是先将其转换为JSON,然后对键进行排序,如下所示:

import json

foo = {None: 7, 'bar': 8}
# {'bar': 8, None: 7}

foo_json = json.dumps(foo)
# '{"bar": 8, "null": 7}'

foo_prime = json.loads(foo_json)
# {'null': 7, 'bar': 8}

foo_sorted = json.dumps(foo_prime, sort_keys=True)
# '{"bar": 8, "null": 7}'

This does change the key (from None/null to 'null' ) but does so consistently. 这确实会更改密钥(从None/null更改为'null' ),但始终如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM