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)

 

你可能感兴趣的:(python)