TypeError: Object of type bytes is not JSON serializable

时间:2021-01-25 10:37:52   收藏:0   阅读:0

0.问题描述

在做一个数据处理的时候,需要将一个XMl的文件解析成一个json,关键是xml的文件格式和json不是一一对应的,需要我一点一点拼接关键信息,组成json文件,最后在写出json文件的时候,我采用了json.dump(result, json_file,indent=4),结果出现了以下的错误:

Traceback (most recent call last):
  File "D:/PycharmProjects/ocr/xmlToJson.py", line 151, in <module>
    parseXmlToJson("D://2", "D://3", "D://output")
  File "D:/PycharmProjects/ocr/xmlToJson.py", line 121, in parseXmlToJson
    json.dump(result, json_file,indent=4)
  File "d:\softwareinstall\python3.7\lib\json\__init__.py", line 179, in dump
    for chunk in iterable:
  File "d:\softwareinstall\python3.7\lib\json\encoder.py", line 431, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "d:\softwareinstall\python3.7\lib\json\encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "d:\softwareinstall\python3.7\lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "d:\softwareinstall\python3.7\lib\json\encoder.py", line 179, in default
    raise TypeError(f‘Object of type {o.__class__.__name__} ‘
TypeError: Object of type bytes is not JSON serializable

1.问题解决

报错信息中显示是类型bytes不是json的可序列化的,这时候我就去观察我在拼凑dict的时候有没有采用bytes这种类型,

技术图片

经过bebug发现确实这转化base64的时候他的结果是bytes的,所以我的将bytes转成str类型即可。

我们只需要在bytes类型后面加上decode()就行,想我这个例子中base64.b64encode(image.read()).decode()

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!