首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >解决 json.dump 报错:TypeError - Object of type xxx is not JSON serializable

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

作者头像
为为为什么
发布于 2022-08-05 10:28:59
发布于 2022-08-05 10:28:59
3.1K0
举报
文章被收录于专栏:又见苍岚又见苍岚

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

自定义序列化方法

代码语言:javascript
复制
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包写入数据时加入

代码语言:javascript
复制
json.dump(final_json, fp, indent=3, cls= MyEncoder)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年5月12日,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 自定义序列化方法
  • 调用json包写入数据时加入
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档