
本文介绍了如何使用 Python 将一个包含多个 JSON 对象的 JSON 文件,分割成多个独立的文件,每个文件包含一个 JSON 对象。通过 json 模块的 load 和 dump 函数,可以轻松读取 JSON 文件内容并将其写入到多个文件中,实现数据的拆分和管理。
读取 JSON 文件并分割
假设我们有一个名为 data.json 的 JSON 文件,其内容是一个包含多个 JSON 对象的数组。我们需要将这个文件分割成多个文件,每个文件对应数组中的一个 JSON 对象,并命名为 data_out_1.json、data_out_2.json 等。
以下是实现此功能的 Python 代码:
import json
# 读取 JSON 文件
with open("data.json", "r") as f_in:
data = json.load(f_in)
# 遍历 JSON 对象数组,并将每个对象写入单独的文件
for i, d in enumerate(data, 1):
with open(f"data_out_{i}.json", "w") as f_out:
json.dump(d, f_out, indent=4)代码解释:
立即学习“Python免费学习笔记(深入)”;
华友协同办公管理系统(华友OA),基于微软最新的.net 2.0平台和SQL Server数据库,集成强大的Ajax技术,采用多层分布式架构,实现统一办公平台,功能强大、价格便宜,是适用于企事业单位的通用型网络协同办公系统。 系统秉承协同办公的思想,集成即时通讯、日记管理、通知管理、邮件管理、新闻、考勤管理、短信管理、个人文件柜、日程安排、工作计划、工作日清、通讯录、公文流转、论坛、在线调查、
- import json: 导入 json 模块,用于处理 JSON 数据。
- with open("data.json", "r") as f_in:: 使用 with open() 语句打开名为 data.json 的文件,并以只读模式 ("r") 打开。f_in 是文件对象,用于读取文件内容。
- data = json.load(f_in): 使用 json.load() 函数从文件对象 f_in 中读取 JSON 数据,并将其解析为 Python 对象(在本例中是一个列表)。
- for i, d in enumerate(data, 1):: 使用 for 循环遍历 data 列表。enumerate(data, 1) 函数返回一个枚举对象,其中 i 是索引(从 1 开始),d 是列表中的每个 JSON 对象。
- with open(f"data_out_{i}.json", "w") as f_out:: 使用 with open() 语句创建一个新的文件,文件名根据索引 i 动态生成,例如 data_out_1.json。文件以写入模式 ("w") 打开。f_out 是文件对象,用于写入文件内容。
- json.dump(d, f_out, indent=4): 使用 json.dump() 函数将 Python 对象 d (即一个 JSON 对象) 写入到文件对象 f_out 中。indent=4 参数用于格式化 JSON 输出,使其更易于阅读。
处理 JSON 字符串
如果 JSON 数据不是存储在文件中,而是存储在一个字符串变量中,例如 json_output,则可以使用 json.loads() 函数将字符串解析为 Python 对象。
import json
json_output = """\
[
{"any": 2023},
{
"dia": 24,
"mes": 1,
"any": 2023,
"mes_referencia": 12,
"any_referencia": 2022,
"calendari_nom": "CCC"
},
{
"dia": 4,
"mes": 12,
"any": 2023,
"mes_referencia": 10,
"any_referencia": 2023,
"calendari_nom": "FFF"
},
{
"dia": 4,
"mes": 1,
"any": 2023,
"mes_referencia": 0,
"any_referencia": 2022,
"calendari_nom": "GAS",
"periode_ref": "TT"
},
{
"dia": 3,
"mes": 10,
"any": 2023,
"mes_referencia": 0,
"any_referencia": 2023,
"calendari_nom": "GAS",
"periode_ref": "22"
}
]"""
data = json.loads(json_output)
for i, d in enumerate(data, 1):
with open(f"data_out_{i}.json", "w") as f_out:
json.dump(d, f_out, indent=4)代码解释:
立即学习“Python免费学习笔记(深入)”;
- data = json.loads(json_output): 使用 json.loads() 函数将 JSON 字符串 json_output 解析为 Python 对象(在本例中是一个列表)。 loads 函数用于从字符串加载 JSON 数据,而 load 函数用于从文件加载 JSON 数据。
注意事项
- 文件路径: 确保文件路径正确,并且 Python 脚本有权限读取和写入文件。
- JSON 格式: 确保 JSON 文件的格式正确,否则 json.load() 函数可能会抛出异常。
- 文件覆盖: 如果输出文件已经存在,将会被覆盖。 如果需要避免覆盖,可以在打开文件时使用 "x" 模式(仅新建文件)。
- 编码问题: 如果 JSON 文件包含非 ASCII 字符,可能需要指定文件编码,例如 open("data.json", "r", encoding="utf-8")。
总结
本文介绍了使用 Python 将 JSON 文件分割成多个文件的两种方法:一种是从文件中读取 JSON 数据,另一种是从 JSON 字符串中读取数据。 通过 json 模块的 load、loads 和 dump 函数,可以轻松实现 JSON 数据的读取、解析和写入,从而实现数据的分割和管理。 在实际应用中,需要根据具体情况选择合适的方法,并注意文件路径、JSON 格式和编码问题。









