python - 如何处理 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)))
它也显示相同的错误
解决方案
您必须使用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))
推荐阅读
- node.js - 如何在节点js中获取客户端的mac地址?
- sql - 将持续时间格式 P0DT0H0M0S(ISO 8601 持续时间格式)转换为小时
- svn - 颠覆:找到整个回购的最后一个日志文件条目?
- kubernetes - K8S 集群:命令 kubeadm join 得到警告并挂起
- multithreading - 如何将十进制数写为 F# 中的原子写入?
- javascript - 合并数组内的对象,数组内的对象
- amazon-s3 - 如何从 codebuild buildspec 获取 S3 对象?(拒绝访问)
- python - 我正在关注 Django 文档 01,但它对我不起作用
- php - 预订系统 - 检查日期是否有空 [Laravel 8]
- jquery - jQuery.repeater 不适用于可排序的 jQuery Ui