解决 json.dump 报错:TypeError - Object of type xxx is not JSON serializable

水深无声 2023-03-12 09:25 97阅读 0赞

在python中导入json包可以方便地操作json文件,但是偶尔会遇到 TypeError: Object of type xxx is not JSON serializable 错误,通常报错的位置是很正常的int或float,本文记录该问题解决方法。

自定义序列化方法

  1. class MyEncoder(json.JSONEncoder):
  2. def default(self, obj):
  3. if isinstance(obj, np.integer):
  4. return int(obj)
  5. elif isinstance(obj, np.floating):
  6. return float(obj)
  7. elif isinstance(obj, np.ndarray):
  8. return obj.tolist()
  9. if isinstance(obj, time):
  10. return obj.__str__()
  11. else:
  12. return super(MyEncoder, self).default(obj)

调用json包时加入

  1. json.dump(final_json, fp, indent=3,cls= MyEncoder)

发表评论

表情:
评论列表 (有 0 条评论,97人围观)

还没有评论,来说两句吧...

相关阅读