Python 字典加载与保存实现:JSON 序列化与自定义编码器

Ryan
Ryan
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍 Python 中字典数据的加载与保存方法。通过 json 模块实现基础读写,并针对 NumPy 整数、浮点数、数组及 datetime 对象提供自定义 JSONEncoder 解决方案,确保复杂数据结构能正确序列化为 JSON 文件。

从 JSON 文件加载字典

在 Python 开发中,将字典数据从 JSON 文件加载到内存是常见操作。以下代码展示了如何使用标准库中的 json 模块完成这一过程。通过 open 函数以只读模式打开文件,并利用 json.load 方法将文件内容解析为字典对象,最终返回该字典供后续使用。


import json

def load_dict(filename):
 '''load dict from json file'''
 with open(filename,"r") as json_file:
  dic = json.load(json_file)
 return dic

保存字典至 JSON 文件及自定义编码器

将字典数据保存为 JSON 文件时,若字典中包含非标准 JSON 类型(如 NumPy 数据类型或日期时间对象),直接使用 json.dump 会引发错误。为此,需要定义一个继承自 json.JSONEncoder 的自定义编码器类 JsonEncoder。在该类的 default 方法中,分别处理 np.integer、np.floating、np.ndarray 和 datetime 类型,将其转换为 Python 原生类型或列表字符串。随后,通过 open 函数以写入模式打开文件,调用 json.dump 并传入自定义编码器类,即可将字典安全地保存为 JSON 文件。


import json
import datetime
import numpy as np

class JsonEncoder(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):         
   return obj.__str__()
  else:
   return super(MyEncoder, self).default(obj)

def save_dict(filename, dic):
 '''save dict into json file'''
 with open(filename,'w') as json_file:
  json.dump(dic, json_file, ensure_ascii=False, cls=JsonEncoder)

上述内容涵盖了 Python 字典与 JSON 文件交互的核心实现,包括基础加载逻辑及针对复杂数据类型的保存策略。希望这些示例能为您的数据处理工作提供有效参考。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表