
在数据处理和管理中,我们经常会遇到包含大量独立记录的json文件,这些记录以数组的形式存储。为了便于后续的独立处理、存储或分发,将这些json数组中的每个对象拆分成单独的json文件是一个常见的需求。python的json模块提供了强大而简洁的工具来完成这项任务。
要实现JSON文件的拆分,我们需要理解JSON数据在Python中的表示:
因此,拆分过程本质上就是遍历一个包含字典的Python列表,并将每个字典序列化为独立的JSON文件。
这是最常见的场景,即您有一个存储在磁盘上的JSON文件,其中包含一个JSON对象数组。
示例JSON文件 (data.json) 内容:
立即学习“Python免费学习笔记(深入)”;
[
{"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 代码实现:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
import json
import os
def split_json_file(input_filepath, output_dir="output_json_files"):
"""
将包含JSON对象数组的文件拆分为多个独立文件。
Args:
input_filepath (str): 输入JSON文件的路径。
output_dir (str): 存储拆分后文件的目录。
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"创建输出目录: {output_dir}")
try:
with open(input_filepath, "r", encoding="utf-8") as f_in:
data = json.load(f_in)
if not isinstance(data, list):
print("警告:输入JSON文件的根元素不是一个列表,无法按预期拆分。")
return
print(f"开始拆分文件 '{input_filepath}'...")
for i, item in enumerate(data, 1): # 从1开始计数,以便生成文件名
output_filename = os.path.join(output_dir, f"data_out_{i}.json")
with open(output_filename, "w", encoding="utf-8") as f_out:
json.dump(item, f_out, indent=4, ensure_ascii=False)
print(f"已生成文件: {output_filename}")
print("所有JSON对象已成功拆分为独立文件。")
except FileNotFoundError:
print(f"错误:文件 '{input_filepath}' 未找到。")
except json.JSONDecodeError:
print(f"错误:文件 '{input_filepath}' 不是一个有效的JSON格式。")
except Exception as e:
print(f"发生未知错误: {e}")
# 假设 data.json 存在于当前目录下
# 创建一个 dummy data.json 文件用于测试
dummy_json_content = """
[
{"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"
}
]
"""
with open("data.json", "w", encoding="utf-8") as f:
f.write(dummy_json_content)
# 调用函数进行拆分
split_json_file("data.json")
# 预期输出示例 (data_out_2.json):
# {
# "dia": 24,
# "mes": 1,
# "any": 2023,
# "mes_referencia": 12,
# "any_referencia": 2022,
# "calendari_nom": "CCC"
# }代码解析:
有时,JSON数据可能不是来自文件,而是以字符串的形式存在于Python变量中(例如,从网络API获取的响应)。
示例JSON字符串 (json_output) 内容:
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"
}
]"""Python 代码实现:
import json
import os
def split_json_string(json_string_data, output_dir="output_json_files_from_string"):
"""
将包含JSON对象数组的字符串数据拆分为多个独立文件。
Args:
json_string_data (str): 包含JSON数据的字符串。
output_dir (str): 存储拆分后文件的目录。
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"创建输出目录: {output_dir}")
try:
data = json.loads(json_string_data)
if not isinstance(data, list):
print("警告:输入JSON字符串的根元素不是一个列表,无法按预期拆分。")
return
print("开始拆分JSON字符串数据...")
for i, item in enumerate(data, 1):
output_filename = os.path.join(output_dir, f"data_out_{i}.json")
with open(output_filename, "w", encoding="utf-8") as f_out:
json.dump(item, f_out, indent=4, ensure_ascii=False)
print(f"已生成文件: {output_filename}")
print("所有JSON对象已成功拆分为独立文件。")
except json.JSONDecodeError:
print("错误:输入的字符串不是一个有效的JSON格式。")
except Exception as e:
print(f"发生未知错误: {e}")
# 定义JSON字符串
json_string_data_example = """\
[
{"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"
}
]"""
# 调用函数进行拆分
split_json_string(json_string_data_example)代码解析: 此场景与从文件读取的主要区别在于使用了 json.loads() 函数。
通过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号