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

问题描述:

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


 

解决办法:

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

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)

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

json.dumps(data, cls=MyEncoder) 

dict to json

def dict_to_json(dict_obj,name, Mycls = None):
    
    js_obj = json.dumps(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 = json.load(js_obj, cls = Mycls)
    return dict_obj


参考:

https://www.jianshu.com/p/0883d6f4bec3

https://www.jianshu.com/p/fcc1204c90c9

https://blog.csdn.net/bear_sun/article/details/79397155/

https://blog.csdn.net/gqixf/article/details/78954021

https://www.cnblogs.com/qiqi-yhq/articles/12557870.html

https://mlog.club/article/1487147

 

你可能感兴趣的:(Python)