如何用Python合并多份同结构JSON文件并提取results数据
Python合并JSON文件提取results字段解决方案
核心思路
遍历目标JSON文件,逐个读取并提取results字段内容,根据需求选择合并所有engagement记录为一个大数组,或者保留每个文件的results数组作为独立单元,最后写入新文件。
方案一:合并所有engagement记录(标准JSON格式)
该方案将所有文件的results中的记录合并到一个数组中,生成合法的JSON文件,适合后续数据处理:
import json import os # 替换为你的JSON文件存放目录 json_directory = "./your_json_files" merged_records = [] # 遍历目录下所有JSON文件 for file_name in os.listdir(json_directory): if file_name.endswith(".json"): file_path = os.path.join(json_directory, file_name) with open(file_path, "r", encoding="utf-8") as file: try: data = json.load(file) # 提取results字段,若不存在则取空列表 merged_records.extend(data.get("results", [])) except json.JSONDecodeError: print(f"跳过格式错误的文件:{file_name}") # 写入合并后的文件 with open("merged_all_engagements.json", "w", encoding="utf-8") as output_file: json.dump(merged_records, output_file, indent=2)
方案二:保留每个文件的results数组(匹配你的预期输出)
若需要保留每个原文件的results数组作为独立单元(如你示例中的格式),可使用以下代码(注意:输出格式非标准JSON,仅匹配你的需求):
import json import os json_directory = "./your_json_files" all_file_results = [] for file_name in os.listdir(json_directory): if file_name.endswith(".json"): file_path = os.path.join(json_directory, file_name) with open(file_path, "r", encoding="utf-8") as file: try: data = json.load(file) all_file_results.append(data.get("results", [])) except json.JSONDecodeError: print(f"跳过格式错误的文件:{file_name}") # 写入按原文件拆分的结果 with open("separate_results.json", "w", encoding="utf-8") as output_file: for index, result_array in enumerate(all_file_results): json.dump(result_array, output_file, indent=2) # 最后一个数组后不加逗号 if index != len(all_file_results) - 1: output_file.write(",\n")
注意事项
- 将
json_directory替换为你的JSON文件实际存放路径,若仅处理指定文件,可直接用文件名列表遍历 - 添加了
try-except块处理JSON格式错误的文件,避免程序崩溃 - 方案二的输出并非标准JSON结构,若需要兼容JSON解析工具,建议优先使用方案一
内容的提问来源于stack exchange,提问作者Opper_Draak
相关产品推荐
相关产品推荐

