base64 to json property in Python

Question:

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?

Asked By: MatnikR

||

Answers:

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))

Answered By: Yeshwanth N

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})
Answered By: perpetualstudent

You should use encoded = base64.b64encode(data).decode()

b64encode() will encode as base64

x.decode() will decode bytes object to unicode string

Answered By: threadfin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.