base64 到 json 属性 在 Python
base64 to json property in Python
我有以下代码:
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
我可以知道如何解决这个问题吗?
如果它是您想要作为 http 响应发送的图像,您不应该这样做 json.dumps,相反您可以发送原始字节并接收它。
但是,如果您仍想这样做,则需要更改为 json.dumps(str(retObj))
base64.b64encode(data)
将以字节为单位输出一个对象
encoded = base64.b64encode(data).decode()
将其转换为字符串
之后您可能需要(很常见)对字符串进行 url 编码
from urllib.parse import urlencode
urlencode({"groupedImage": encoded})
我有以下代码:
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
我可以知道如何解决这个问题吗?
如果它是您想要作为 http 响应发送的图像,您不应该这样做 json.dumps,相反您可以发送原始字节并接收它。
但是,如果您仍想这样做,则需要更改为 json.dumps(str(retObj))
base64.b64encode(data)
将以字节为单位输出一个对象
encoded = base64.b64encode(data).decode()
将其转换为字符串
之后您可能需要(很常见)对字符串进行 url 编码
from urllib.parse import urlencode
urlencode({"groupedImage": encoded})