Python---Json报错TypeError: Object of type ‘bytes‘ is not JSON serializable

Json报错TypeError: Object of type ‘bytes’ is not JSON serializable

TypeError: Object of type ‘bytes’ is not JSON serializable

因为json.dumps函数发现字典里面有bytes类型的数据,因此无法编码,只要在编码函数之前写一个编码类就行了,只要检查到了是bytes类型的数据就把它转化成str类型。

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)

result = MyEncoder().default(bytes_data)

或者简单一点:

# bytes 转 str
string= str(bdata, encoding='utf-8')

# str 转 bytes
bdata = bytes(string, encoding = "utf8")

参考博客:TypeError: Object of type ‘bytes’ is not JSON serializable

你可能感兴趣的:(Python,python)