尝试使用 json.dumps() 将具有 bytes 类型键的字典对象转换为 json。字典对象的格式事先未知。在使用 json.dumps(Convert bytes embedding 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
Run Code Online (Sandbox Code Playgroud)
从上面输出
{"name": "bob", "age": 33, "attributes": {"hair": "brown", "arms": 2}}
Traceback …Run Code Online (Sandbox Code Playgroud)