使用json模块的dump()方法可将字典写入JSON文件,配合ensure_ascii=False和encoding='utf-8'解决中文编码问题;datetime等非序列化对象需通过default函数或自定义JSONEncoder转换;处理大文件时可用ijson库实现流式解析,降低内存占用。

Python中将字典写入JSON文件,核心在于使用
json
dump()
dumps()
dump()
dumps()
解决方案:
import json
# 示例字典
data = {
"name": "张三",
"age": 30,
"city": "北京"
}
# 写入JSON文件
def write_json_file(data, filename="data.json"):
"""
将Python字典写入JSON文件。
"""
try:
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4) # indent参数用于美化JSON格式,ensure_ascii=False处理中文
print(f"数据已成功写入到 {filename}")
except Exception as e:
print(f"写入JSON文件时发生错误: {e}")
# 调用函数
write_json_file(data)
# 或者使用 dumps() 方法,将字典转换为 JSON 字符串
json_string = json.dumps(data, ensure_ascii=False, indent=4)
print(json_string)
如何处理JSON文件写入时的编码问题?
编码问题是JSON操作中常见的坑。默认情况下,
json.dump()
\uXXXX
json.dump()
ensure_ascii=False
encoding='utf-8'
立即学习“Python免费学习笔记(深入)”;
如果字典中包含datetime对象,如何序列化?
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
Python的
datetime
datetime
import json
from datetime import datetime
def datetime_converter(o):
if isinstance(o, datetime):
return o.isoformat()
raise TypeError("Object of type '%s' is not JSON serializable" % type(o).__name__)
data = {
"event": "会议",
"time": datetime.now()
}
# 使用default参数指定转换函数
json_string = json.dumps(data, default=datetime_converter, ensure_ascii=False, indent=4)
print(json_string)
# 或者,可以自定义一个JSONEncoder
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_string = DateTimeEncoder().encode(data)
print(json_string)如何处理JSON文件过大的情况?
当处理大型JSON文件时,一次性加载到内存可能导致性能问题。这时可以考虑使用
ijson
ijson
import ijson
# 从文件中逐个解析 JSON 对象
with open('large.json', 'r') as f:
for record in ijson.items(f, 'records.item'): # 'records.item' 是 JSON 数据的路径
print(record)
# 在这里处理每个 record此外,还可以考虑使用gzip压缩JSON文件,减小文件大小,但需要在读取时进行解压。
以上就是python如何将字典写入json文件_python字典数据保存为JSON文件教程的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号