python3运行报错:TypeError: Object of type 'type' is not JSON serializable解决方法

作者: xiaozhu 发布时间: 2022-10-27 浏览: 2818 次 编辑

python3运行报错:TypeError: Object of type 'type' is not JSON serializable解决方法

报这个错的原因:

因为json.dumps函数发现字典里面有bytes类型的数据,无法编码。

解决方法:

在编码函数之前写一个编码类,只要检查到了是bytes类型的数据就把它转化成str类型。

这个编码类代码示例如下:

#!/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)