TypeError: Object of type bytes is not JSON serializable - python 3 - try to post base64 image data

Viewed 3023

i received this error after try convert data to json to post request

TypeError: Object of type 'bytes' is not JSON serializable

my code

dict_data: dict = {
  'img': base64.b64encode(urlopen(obj['recognition_image_path']).read())
}
json_data: str = json.dumps(dict_data)

i read image from url, convert it to base64, after i received error when try convert data to json. Please help

2 Answers

You need to convert to string first by calling .decode, since you can't JSON-serialize a bytes without knowing its encoding.

(base64.b64encode returns a bytes, not a string.)

import base64
from urllib.request import urlopen
import json

dict_data: dict = {
  'img': base64.b64encode(urlopen(obj['recognition_image_path']).read()).decode('utf8')
}
json_data: str = json.dumps(dict_data)

edit: rewrite answer to address actual question, encode/decode

I will do it in a two step process:

  1. First encode the image file into BASE64
  2. Then decode the encoded file

And then transmit back the JSON data using the decoded file.

Here is an example:

Let's say the image file is is_image_file

  1. Encode the image file by:

enc_image_file = base64.b64encode(is_image_file.read())

  1. Next decode it by:

send_image_file = enc_image_file.decode()

Finally transmit the data using send_image_file as JsonResponse to wherever it would be used.

Of course, add import base64 before calling the function.

Note: Using json.dumps(dict_data) one gets a string which will not load the image/s.

Related