Reputation: 191
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?
Upvotes: 2
Views: 381
Reputation: 163
You should use encoded = base64.b64encode(data).decode()
b64encode()
will encode as base64
x.decode()
will decode bytes object to unicode string
Upvotes: 1
Reputation: 5607
base64.b64encode(data)
will output an object in bytes
encoded = base64.b64encode(data).decode()
converts it to string
after that you might need (quite common) to do url encoding to the string
from urllib.parse import urlencode
urlencode({"groupedImage": encoded})
Upvotes: 1
Reputation: 570
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.
However if you still want to do you'll need to change to json.dumps(str(retObj))
Upvotes: 1