解决 json.dump 报错:TypeError - Object of type xxx is not JSON serializable
在python中导入json包可以方便地操作json文件,但是偶尔会遇到 TypeError: Object of type xxx is not JSON serializable 错误,通常报错的位置是很正常的int或float,本文记录该问题解决方法。
自定义序列化方法
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(MyEncoder, self).default(obj)
调用json包时加入
json.dump(final_json, fp, indent=3,cls= MyEncoder)
还没有评论,来说两句吧...