Python中的base64到json属性



我有以下代码:

data = open('/tmp/books_read.png', "rb").read()
encoded = base64.b64encode(data)
retObj = {"groupedImage": encoded}
return func.HttpResponse(
json.dumps(retObj),
mimetype="application/json",
status_code=200)

并抛出以下错误:

Object of type bytes is not JSON serializable Stack

我可以知道该怎么修吗?

base64.b64encode(data)将以字节输出对象

encoded = base64.b64encode(data).decode()将其转换为字符串

之后,您可能需要(非常常见(对字符串进行url编码

from urllib.parse import urlencode
urlencode({"groupedImage": encoded})

如果是要作为http响应发送的图像,则不应该执行json.dumps,而是可以发送原始字节并接收它。

但是,如果你仍然想这样做,你需要更改为json.dumps(str(retObj))

您应该使用encoded = base64.b64encode(data).decode()

b64encode()将编码为base64

x.decode()将字节对象解码为unicode字符串

最新更新