【问题标题】:Python errors in file encode文件编码中的 Python 错误
【发布时间】:2019-04-23 01:30:49
【问题描述】:

这是我的代码:

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

【问题讨论】:

  • 错误告诉你究竟出了什么问题。您的 dict 包含 bytes 对象,json.dumps() 无法序列化。你如何解决这个问题取决于你到底需要什么。
  • 你可以看这里:link,有一个很好的解决方案

标签: python encode


【解决方案1】:

这里的问题是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

【讨论】:

    【解决方案2】:

    你在这里只缺少一个方面:当你使用 .encodestring 时,你有一个字节对象作为结果,并且字节在 python 3 中不是 json 可序列化的。

    你可以解决它只是编码你的数据[“字节”]:

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

    我假设你总是会在“bytes”变量中收到一个字节对象,否则你应该为对象的类型添加一个检查器,当它已经是一个字符串时不要编码。

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 2012-07-09
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多