简体   繁体   English

base64 到 json 属性在 Python

[英]base64 to json property in Python

I have the following code:我有以下代码:

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)

... and it throws the following error: ...并引发以下错误:

Object of type bytes is not JSON serializable Stack

May I know how do I fix this?我可以知道如何解决这个问题吗?

If it is image which you want to send as http reponse you shouldn't be doing json.dumps, instead you can send raw bytes and receive it.如果它是您想要作为 http 响应发送的图像,则您不应该执行 json.dumps,而是可以发送原始字节并接收它。

However if you still want to do you'll need to change to json.dumps(str(retObj))但是,如果您仍然想这样做,则需要更改为json.dumps(str(retObj))

base64.b64encode(data) will output an object in bytes base64.b64encode(data)将 output 和 object 以字节为单位

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

after that you might need (quite common) to do url encoding to the string之后,您可能需要(很常见)对字符串进行 url 编码

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

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

b64encode() will encode as base64 b64encode()将编码为 base64

x.decode() will decode bytes object to unicode string x.decode()将字节 object 解码为 unicode 字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM