Python轻松合并两个JSON文件内容:实用方法详解**
在数据处理和日常开发中,我们经常会遇到需要将多个JSON文件的内容合并成一个的情况,JSON(JavaScript Object Notation)因其轻量级、易读易写的特性,成为数据交换的常用格式,Python作为一门功能强大的编程语言,提供了多种便捷的方法来合并JSON文件内容,本文将详细介绍几种常用的Python合并JSON文件的方法,并附上示例代码,帮助你轻松应对这一需求。
逐个读取、手动合并(适用于简单结构)
这种方法最直观,适用于两个JSON文件结构相对简单,或者你希望对合并过程有更精细控制的场景,基本思路是:
- 读取第一个JSON文件的内容到Python对象(通常是字典或列表)。
- 读取第二个JSON文件的内容到另一个Python对象。
- 根据你的需求,将这两个Python对象进行合并(将字典的键值对相加,将列表元素合并等)。
- 将合并后的Python对象写入一个新的JSON文件。
示例代码:
假设我们有两个JSON文件:file1.json 和 file2.json。
file1.json 内容:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
file2.json 内容:
{
"name": "Bob",
"age": 25,
"country": "USA"
}
如果我们希望将这两个字典合并,键相同则后者的值覆盖前者,可以这样操作:
import json
def merge_json_files_simple(file1_path, file2_path, output_path):
"""
简单合并两个JSON文件(假设内容为字典)
:param file1_path: 第一个JSON文件路径
:param file2_path: 第二个JSON文件路径
:param output_path: 输出JSON文件路径
"""
try:
# 读取第一个JSON文件
with open(file1_path, 'r', encoding='utf-8') as f1:
json_data1 = json.load(f1)
# 读取第二个JSON文件
with open(file2_path, 'r', encoding='utf-8') as f2:
json_data2 = json.load(f2)
# 合并字典:如果json_data1是字典,json_data2也是字典
# 使用update方法,json_data2的键值会更新到json_data1中,不存在的键会添加
if isinstance(json_data1, dict) and isinstance(json_data2, dict):
merged_data = {**json_data1, **json_data2} # 或者 json_data1.update(json_data2) 然后用json_data1
# 注意:update是原地操作,如果不想改变json_data1,可以使用解包或copy
merged_data = json_data1.copy()
merged_data.update(json_data2)
else:
print("警告:JSON文件内容不是字典,无法使用此方法合并。")
return
# 将合并后的数据写入新的JSON文件
with open(output_path, 'w', encoding='utf-8') as out_file:
json.dump(merged_data, out_file, indent=4, ensure_ascii=False)
print(f"文件合并成功,结果已保存到 {output_path}")
except FileNotFoundError:
print("错误:指定的文件未找到。")
except json.JSONDecodeError:
print("错误:JSON文件格式不正确。")
except Exception as e:
print(f"发生未知错误: {e}")
# 使用示例
merge_json_files_simple('file1.json', 'file2.json', 'merged_file1.json')
合并后的 merged_file1.json
{
"name": "Bob",
"age": 25,
"city": "New York",
"country": "USA"
}
注意: 这种方法如果两个JSON文件内容都是列表,我们可以使用 操作符合并列表。
使用 jsonmerge 库(适用于复杂结构和自定义合并规则)
如果JSON文件结构比较复杂,或者需要更灵活的合并策略(数组是追加还是替换,嵌套对象如何处理等),使用专门的库会更方便。jsonmerge 是一个不错的选择。
安装 jsonmerge 库:
pip install jsonmerge
示例代码:
假设我们有两个JSON文件,其中一个包含数组,我们希望将数组元素合并。
file3.json 内容:
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
],
"version": 1
}
file4.json 内容:
{
"users": [
{"id": 3, "name": "Charlie"}
],
"version": 2
}
我们希望 users 数组能够追加合并:
import json
from jsonmerge import Merger
def merge_json_files_with_library(file1_path, file2_path, output_path, merge_schema):
"""
使用jsonmerge库合并两个JSON文件
:param file1_path: 第一个JSON文件路径
:param file2_path: 第二个JSON文件路径
:param output_path: 输出JSON文件路径
:param merge_schema: 合并schema定义
"""
try:
# 读取第一个JSON文件作为基础
with open(file1_path, 'r', encoding='utf-8') as f1:
base_data = json.load(f1)
# 读取第二个JSON文件
with open(file2_path, 'r', encoding='utf-8') as f2:
new_data = json.load(f2)
# 创建Merger对象
merger = Merger(merge_schema)
# 合并数据
merged_data = merger.merge(base_data, new_data)
# 将合并后的数据写入新的JSON文件
with open(output_path, 'w', encoding='utf-8') as out_file:
json.dump(merged_data, out_file, indent=4, ensure_ascii=False)
print(f"文件合并成功,结果已保存到 {output_path}")
except FileNotFoundError:
print("错误:指定的文件未找到。")
except json.JSONDecodeError:
print("错误:JSON文件格式不正确。")
except Exception as e:
print(f"发生未知错误: {e}")
# 定义合并schema,这里指定users字段是数组,且要追加
# "mergeStrategy": "mergebyid" 也可以,如果需要根据ID合并
merge_schema = {
"properties": {
"users": {
"mergeStrategy": "arrayappend" # 简单追加
# 或者 "mergeStrategy": "mergebyid", 如果需要更复杂的基于ID的合并
}
}
}
# 使用示例
merge_json_files_with_library('file3.json', 'file4.json', 'merged_file2.json', merge_schema)
合并后的 merged_file2.json
{
"users": [
{
"id": 1,
"name": "Alice"
},
{
"id": 2,
"name": "Bob"
},
{
"id": 3,
"name": "Charlie"
}
],
"version": 2
}
jsonmerge 提供了多种合并策略,如 arrayappend(追加数组)、mergebyid(根据ID合并对象)、overwrite(覆盖)等,非常灵活。
合并JSON数组到列表(适用于多个JSON数组合并)
如果两个JSON文件的内容都是数组,并且你希望将这两个数组合并为一个更大的数组,操作也很简单。
示例代码:
假设 合并代码:array1.json
[1, 2, 3]
array2.json
[4, 5, 6]
import json
def merge_json_arrays(file1_path, file2_path, output_path):
"""
合并两个JSON数组文件为一个更大的数组
:param file1_path: 第一个JSON数组文件路径
:param file2_path: 第二个JSON数组文件路径
:param output_path: 输出JSON数组文件路径
"""
try:
with open(file1_path, 'r', encoding='utf-8') as f1:
array1 = json.load(f1)
with open(file2_path, 'r', encoding='utf-8') as f2:
array2 = json.load(f2)
if not isinstance(array1, list) or not isinstance(array2, list):
print("错误:指定的文件内容不是JSON数组。")
return
merged_array = array1 + array2
with open(output_path, 'w', encoding='utf-8') as out_file:
json.dump(merged_array, out_file, indent=4, ensure_ascii=False



还没有评论,来说两句吧...