
在数据处理和管理中,我们经常会遇到包含大量独立记录的json文件,这些记录通常被封装在一个json数组中。例如,一个日志文件可能包含多个事件记录,一个api响应可能返回多个用户对象。当需要对这些独立记录进行单独处理、存储、传输或分析时,将大型json数组拆分成多个独立文件就显得尤为重要。这样做的好处包括:
Python凭借其强大的json模块和灵活的文件操作能力,成为实现这一任务的理想工具。
进行本教程的学习和实践,您只需要具备以下条件:
一个典型的包含多个对象的JSON数组结构如下:
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" },
{ "id": 3, "name": "Charlie" }
]当Python的json模块解析这个JSON数组时,它会将其转换为一个Python列表(list),列表中的每个元素都是一个Python字典(dict),对应于JSON数组中的一个对象。
立即学习“Python免费学习笔记(深入)”;
我们的目标是:
我们将通过两种常见的场景来演示如何拆分JSON文件:从现有JSON文件加载数据,以及从Python字符串变量加载JSON数据。
假设您有一个名为 input.json 的文件,内容如下:
input.json:
[
{"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"
}
]以下是拆分该文件的Python代码:
import json
import os
# 定义输入文件路径和输出目录
input_file_path = "input.json"
output_directory = "output_json_files"
# 确保输出目录存在
if not os.path.exists(output_directory):
os.makedirs(output_directory)
try:
with open(input_file_path, "r", encoding="utf-8") as f_in:
data = json.load(f_in) # 加载整个JSON文件内容到Python列表
# 遍历列表中的每个字典(即每个JSON对象)
for i, item_data in enumerate(data, 1):
# 构建输出文件名,例如:data_out_1.json, data_out_2.json
output_file_name = f"data_out_{i}.json"
output_file_path = os.path.join(output_directory, output_file_name)
with open(output_file_path, "w", encoding="utf-8") as f_out:
# 将单个字典写入新的JSON文件
# indent=4 使输出的JSON文件格式化,更易读
json.dump(item_data, f_out, indent=4, ensure_ascii=False)
print(f"已生成文件: {output_file_path}")
except FileNotFoundError:
print(f"错误:文件 '{input_file_path}' 未找到。请确保文件存在。")
except json.JSONDecodeError:
print(f"错误:文件 '{input_file_path}' 不是一个有效的JSON格式。")
except Exception as e:
print(f"发生未知错误: {e}")
运行上述代码后,output_json_files 目录下将生成多个文件,例如 data_out_1.json、data_out_2.json 等。其中 data_out_2.json 的内容将是:
output_json_files/data_out_2.json:
{
"dia": 24,
"mes": 1,
"any": 2023,
"mes_referencia": 12,
"any_referencia": 2022,
"calendari_nom": "CCC"
}有时,JSON数据可能不是存储在文件中,而是以字符串的形式存在于Python变量中(例如,从API请求的响应)。在这种情况下,我们可以使用 json.loads() 方法来解析字符串。
import json
import os
# 定义包含JSON数据的字符串
json_string_data = """\
[
{"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"
}
]"""
output_directory = "output_json_from_string"
# 确保输出目录存在
if not os.path.exists(output_directory):
os.makedirs(output_directory)
try:
# 从字符串加载JSON数据
data = json.loads(json_string_data)
for i, item_data in enumerate(data, 1):
output_file_name = f"data_string_out_{i}.json"
output_file_path = os.path.join(output_directory, output_file_name)
with open(output_file_path, "w", encoding="utf-8") as f_out:
json.dump(item_data, f_out, indent=4, ensure_ascii=False)
print(f"已生成文件: {output_file_path}")
except json.JSONDecodeError:
print("错误:提供的字符串不是一个有效的JSON格式。")
except Exception as e:
print(f"发生未知错误: {e}")
通过本教程,您已经学会了如何使用Python的json模块将一个包含多个JSON对象的数组拆分成一系列独立的JSON文件。无论是从文件加载还是从字符串加载JSON数据,核心思想都是将其解析为Python列表,然后遍历列表中的每个字典,并将其单独写入新文件。这种方法在处理和管理大型JSON数据集时非常实用,能够提高数据处理的效率和灵活性。记住在实际应用中考虑错误处理、文件路径管理和输出格式等细节,以构建更加健壮和用户友好的解决方案。
以上就是Python教程:将JSON数组拆分为多个独立文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号