解决:TypeError: Object of type xxx

2019-05-17  本文已影响0人  风筝flying

问题描述

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

解决办法

自定义序列化方法

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()
        if isinstance(obj, time):
            return obj.__str__()
        else:
            return super(NpEncoder, self).default(obj)

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

json.dumps(data, cls=MyEncoder) 
上一篇下一篇

猜你喜欢

热点阅读