首页 > 解决方案 > 如何处理 TypeError:'bytes' 类型的对象不是 JSON 可序列化的?

问题描述

尝试将输出转换为 Json 格式但出现错误。删除 json.dump 后,将数据转换为 base64 格式。但是当使用 json.dump 它显示错误。

代码:

import json 
import base64

with open(r"C:/Users/Documents/pdf2txt/outputImage.jpg","rb") as img:
    image = base64.b64encode(img.read())
    data['ProcessedImage'] = image

print(json.dump(data)

输出:

TypeError: Object of type 'bytes' is not JSON serializable

使用时:

print(json.dumps(dict(data)))

它也显示相同的错误

标签: pythonjsonpython-3.xserializationbase64

解决方案


您必须使用str.decode()方法。

您正在尝试将字节类型的对象序列化为 JSON 对象。JSON 模式中没有这样的东西。所以你必须先将字节转换为字符串。

此外,您应该使用json.dumps()而不是 json.dump() 因为您不想写入文件。

在您的示例中:

import json 
import base64

with open(r"C:/Users/Documents/pdf2txt/outputImage.jpg", "rb") as img:
    image = base64.b64encode(img.read())
    data['ProcessedImage'] = image.decode() # not just image

print(json.dumps(data))

推荐阅读