0

this is my code:

prettyPicture(clf, features_test, labels_test) output_image("F:/test.png", "png", open("F:/test.png", "rb").read())

def output_image(name, format, bytes):
    image_start = "BEGIN_IMAGE_f9825uweof8jw9fj4r8"
    image_end = "END_IMAGE_0238jfw08fjsiufhw8frs"
    data = {}
    data['name'] = name
    data['format'] = format
    data['bytes'] = base64.encodestring(bytes)
    print(image_start + json.dumps(data) + image_end)

this errors is:

 Traceback (most recent call last):
 File "studentMain.py", line 41, in <module>
 output_image("F:/test.png", "png", open("F:/test.png", "rb").read())
 File "F:\Demo\class_vis.py", line 69, in output_image
 print(image_start + json.dumps(data) + image_end)
 File "C:\Users\Tony\AppData\Local\Programs\Python\Python36- 
32\lib\json\__init__.py", line 231, in dumps
 return _default_encoder.encode(obj)
 File "C:\Users\Tony\AppData\Local\Programs\Python\Python36- 
32\lib\json\encoder.py", line 199, in encode
 chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Tony\AppData\Local\Programs\Python\Python36- 
32\lib\json\encoder.py", line 257, in iterencode
 return _iterencode(o, 0)
 File "C:\Users\Tony\AppData\Local\Programs\Python\Python36- 
 32\lib\json\encoder.py", line 180, in default
  o.__class__.__name__)
 TypeError: Object of type 'bytes' is not JSON serializable
  • 1
    The error tells you exactly what's wrong. Your dict contains a `bytes` object, which `json.dumps()` can't serialize. How you resolve that depends on what exactly you need. – glibdud Nov 20 '18 at 15:08
  • 1
    you can look here: [link](https://stackoverflow.com/questions/37225035/serialize-in-json-a-base64-encoded-data), there is a good solution – nerd100 Nov 20 '18 at 15:11

2 Answers2

0

The issue here is that base64.encodestring() returns a bytes object, not a string.

Try:

data['bytes'] = base64.encodestring(bytes).decode('ascii')

Check out this question and answer for a good explanation of why this is: Why does base64.b64encode() return a bytes object?

Also see: How to encode bytes in JSON? json.dumps() throwing a TypeError

Hal Jarrett
  • 825
  • 9
  • 19
0

You're only missing one aspect here: When you use .encodestring, you have a bytes object as result, and bytes are not json serializable in python 3.

You can solve it just encoding your data["bytes"]:

data['bytes'] = base64.encodestring(bytes).decode("utf-8")

I'm assuming you'll always receive a bytes object at the "bytes" variable, otherwise you should add a checker for the type of the object, and not encoding when it's already a string.

Luan Naufal
  • 1,346
  • 9
  • 15