python3運行報錯:TypeError: Object of type 'type' is not JSON serializable解決方法


首先網上大多數博客沒有明確說明問題的來源

  • 這個問題是由於json.dumps()函數引起的。dumps是將dict數據轉化為str數據,但是dict數據中包含byte數據所以會報錯。
  • 解決:編寫一個解碼類 遇到byte就轉為str

1、新建一個.py文件

myEncoder.py

# -*- coding:utf-8 -*-
# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import json


class MyEncoder(json.JSONEncoder):

    def default(self, obj):
        """
        只要檢查到了是bytes類型的數據就把它轉為str類型
        :param obj:
        :return:
        """
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        return json.JSONEncoder.default(self, obj)

2、在你發生錯誤的文件當中 比如a.py

  • 第一步:from myEncoder import MyEncoder
  • 第二步:將json.dumps(data)改寫為json.dumps(data,cls=MyEncoder,indent=4)

3、至於json.dumps函數里面的cls,indent參數請自行查詢其他博客。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM