解决TypeError: Object of type xxx is not JSON serializable语法错误的问题

时间:2025-05-07 14:39:09

问题描述:

在导入Python json包,调用/dumps函数时,可能会遇到TypeError: Object of type xxx is not JSON serializable错误,也就是无法序列化某些对象格式。


 

解决办法:

默认的编码函数很多数据类型都不能编码,自定义序列化,因此可以自己写一个Myencoder去继承,具体如下:

class MyEncoder():
    def default(self, obj):
        if isinstance(obj, ):
            return int(obj)
        elif isinstance(obj, ):
            return float(obj)
        elif isinstance(obj, ):
            return ()
        else:
            return super(MyEncoder, self).default(obj)

然后在调用/dumps时,指定使用自定义序列化方法

(data, cls=MyEncoder) 

dict to json

def dict_to_json(dict_obj,name, Mycls = None):
    
    js_obj = (dict_obj, cls = Mycls, indent=4)
    
    with open(name, 'w') as file_obj:
        file_obj.write(js_obj)

json to dict

def json_to_dict(filepath, Mycls = None):
    with open(filepath,'r') as js_obj:
        dict_obj = (js_obj, cls = Mycls)
    return dict_obj


参考:

/p/0883d6f4bec3

/p/fcc1204c90c9

/bear_sun/article/details/79397155/

/gqixf/article/details/78954021

/qiqi-yhq/articles/

/article/1487147