在尝试将数据转换为json请求后,我收到了此错误。
TypeError:类型为“字节”的对象不能被JSON序列化
我的代码
dict_data: dict = {
'img': base64.b64encode(urlopen(obj['recognition_image_path']).read())
}
json_data: str = json.dumps(dict_data)我从url读取图像,并将其转换为base64,在尝试将数据转换为json时收到错误后。请帮帮忙
发布于 2020-08-24 03:57:50
您需要首先通过调用string来转换为.decode,因为您不能在不知道bytes编码的情况下序列化它。
(base64.b64encode返回一个bytes,而不是string。)
import base64
from urllib.request import urlopen
import json
dict_data: dict = {
'img': base64.b64encode(urlopen(obj['recognition_image_path']).read()).decode('utf8')
}
json_data: str = json.dumps(dict_data)编辑:重写答案以解决实际问题,编码/解码
发布于 2022-07-09 07:53:56
我将分两步完成:
然后使用解码的文件传回JSON数据。
这里有一个例子:
假设图像文件是is_image_file
对图像文件进行编码
enc_image_file = base64.b64encode(is_image_file.read())
send_image_file = enc_image_file.decode()
最后,将使用data作为JsonResponse的send_image_file传输到使用它的任何地方。
当然,在调用函数之前添加import base64。
注意:使用json.dumps(dict_data) one的将获得一个不会加载图像/s的字符串。
https://stackoverflow.com/questions/63554221
复制相似问题