Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 231
Hoáng Trò Avatar asked Jun 15 '26 19:06

Hoáng Trò


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

like image 185
ATOMP Avatar answered Jun 17 '26 09:06

ATOMP


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.

like image 21
wsrt Avatar answered Jun 17 '26 09:06

wsrt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!