小编mr1*_*r19的帖子

字典上的 json.dumps 以字节为键

尝试使用 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)

python json python-3.x

7
推荐指数
2
解决办法
4269
查看次数

标签 统计

json ×1

python ×1

python-3.x ×1