1. 运行下面代码
import json
import datetime
class NpEncoder(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()
        elif isinstance(obj, datetime.datetime):
        	return obj.strftime('%Y-%m-%dT%H:%M:%S')
        else:
            return super(NpEncoder, self).default(obj)
  1. 然后使用dumps方法(我们可以直接把dict直接序列化为json对象)加上 cls=NpEncoder,data就可以正常序列化了, 并导出 json 文件。
with open("write_json.json", "w", encoding='utf-8') as f:#读的时候也需要用utf-8
    # json.dump(dict_, f)  # 写为一行
    json.dump(json_dict_2, f, indent=2, sort_keys=True, ensure_ascii=False, cls=NpEncoder)  # 写为多行

参考链接
链接

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐