Reputation: 693
I'm building a web application that send some information to an API (API Gateway of AWS) and it receive back an image and some informations (strings) about that image. The strings and the image are generated by a lambda function (AWS service) written in python.
Reading this I converted my image into Base64 encoding using base64 library and send it as a part of my json response, but i get Object of type bytes is not JSON serializable
, how can i solve this?
The answer to this question shows code that does the same thing my code does, but in the comments of that answer it says that code works, while mine doesn't, am I doing something wrong?
This is my code:
def f():
...
bio = BytesIO()
plt.savefig(bio, format="png")
bio.seek(0)
my_base64_jpgData = base64.b64encode(bio.read())
result["image"] = my_base64_jpgData
return result
def lambda_handler(event, context):
body = event["body"]
result = handler(body)
return {
'statusCode': 200,
'body': json.dumps(result)
}
If I test this locally i can avoid doing json.dumps()
and return only result
, but trying the same code in a lambda function make it fails because (i think) the lambda function before sending the response apply json.dumps to it.
EDIT: Also the answer to this question says to do what I did (use base64) but I don't understand why it doesn't work for me
Upvotes: 2
Views: 2661
Reputation: 238081
b64encode returns bytes. To convert it to str
the following should be enough:
result["image"] = my_base64_jpgData.decode()
Subsequently, your code could be:
def f():
...
bio = BytesIO()
plt.savefig(bio, format="png")
bio.seek(0)
my_base64_jpgData = base64.b64encode(bio.read())
result["image"] = my_base64_jpgData.decode()
return result
def lambda_handler(event, context):
body = event["body"]
result = handler(body)
return {
'statusCode': 200,
'body': json.dumps(result)
}
Upvotes: 2