【发布时间】:2019-11-22 15:38:49
【问题描述】:
尝试使用 json.dumps() 将带有字节类型键的字典对象转换为 json。字典对象的格式事先是未知的。在使用 json.dumps (Convert bytes embedded in list (or dict) to str for use with json.dumps) 时找到了具有字节值的数组或字典的解决方案,但没有找到字节键的解决方案。
import json
class BytesDump(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bytes):
return obj.decode()
return json.JSONEncoder.default(self, obj)
foo = {'name': b'bob', 'age': 33, 'attributes': {'hair': b'brown', 'arms': 2}}
bar = {b'name': b'bob', b'age': 33, b'attributes': {b'hair': b'brown', b'arms': 2}}
print(json.dumps(foo, cls=BytesDump)) # this works
print(json.dumps(bar, cls=BytesDump)) # this doesn't work
上面的输出
{"name": "bob", "age": 33, "attributes": {"hair": "brown", "arms": 2}}
Traceback (most recent call last):
File "./test.py", line 15, in <module>
print(json.dumps(bar, cls=BytesDump))
File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
TypeError: keys must be a string
【问题讨论】:
标签: python json python-3.x