文件编码中的Python错误

时间:2018-11-20 15:01:31

标签: python encode

这是我的代码:

  

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)

此错误是:

 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

2 个答案:

答案 0 :(得分:0)

这里的问题是base64.encodestring()返回一个bytes对象,而不是字符串。

尝试:

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

查看此问题并回答,以很好地解释其原因: Why does base64.b64encode() return a bytes object?

另请参阅:How to encode bytes in JSON? json.dumps() throwing a TypeError

答案 1 :(得分:0)

您在这里只缺少一个方面:使用.encodestring时,结果是一个字节对象,并且字节在python 3中无法json可序列化。

您只需编码数据即可解决它[“ bytes”]:

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

我假设您将始终在“ bytes”变量处收到一个bytes对象,否则您应该为该对象的类型添加一个检查器,而不是在它已经是字符串时不进行编码。