1. 程式人生 > 其它 >TypeError Object of type bytes is not JSON serializable

TypeError Object of type bytes is not JSON serializable

技術標籤:pythonpythonjson

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()