使用Python合并多个JSON文件夹中的文件

1.合并完成后成为一个列表

import os
import json

def merge_json_folder(folder_path, output_file):
    json_files = [f for f in os.listdir(folder_path) if f.endswith('.json')]  # 获取文件夹中的所有 JSON 文件路径

    merged_data = []  # 创建一个空列表,用于存储合并后的 JSON 数据

    for file in json_files:
        file_path = os.path.join(folder_path, file)  # 构建完整的文件路径
        with open(file_path, 'r') as json_file:
            data = json.load(json_file)  # 读取 JSON 文件并解析为 Python 对象
            merged_data.append(data)  # 将解析后的 JSON 数据添加到列表中

    # 将合并后的数据转换为 JSON 字符串
    merged_json = json.dumps(merged_data, indent=4)

    # 将合并后的 JSON 字符串写入目标文件
    with open(output_file, 'w') as output:
        output.write(merged_json)

    print("JSON 文件合并完成!")

# 使用示例
folder_path = "json_folder"  # 存放 JSON 文件的文件夹路径
output_file = "merged.json"  # 合并后的 JSON 文件路径
merge_json_folder(folder_path, output_file)

2.合并完成后保留原格式

import os
import json

def merge_json_folder(folder_path, output_file):
    json_files = [f for f in os.listdir(folder_path) if f.endswith('.json')]  # 获取文件夹中的所有 JSON 文件路径

    merged_data = []  # 创建一个空列表,用于存储合并后的 JSON 数据

    for file in json_files:
        file_path = os.path.join(folder_path, file)  # 构建完整的文件路径
        with open(file_path, 'r') as json_file:
            data = json_file.read()  # 读取 JSON 文件内容
            merged_data.append(data)  # 将 JSON 数据添加到列表中

    # 将列表中的 JSON 数据写入目标文件
    with open(output_file, 'w') as output:
        output.write('\n'.join(merged_data))

    print("JSON 文件合并完成!")

# 使用示例
folder_path = "json_folder"  # 存放 JSON 文件的文件夹路径
output_file = "merged.json"  # 合并后的 JSON 文件路径
merge_json_folder(folder_path, output_file)

物联沃分享整理
物联沃-IOTWORD物联网 » 使用Python合并多个JSON文件夹中的文件

发表评论