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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值