我们可以通过Python的json模块将JSON文件转换为Python中的字典类型进行比较和操作。然后使用Python的条件语句和文件操作,将结果写入第三个JSON文件。
示例代码如下:
import json
# 从第一个JSON文件加载数据到字典1中
with open('file1.json', 'r') as f1:
dict1 = json.load(f1)
# 从第二个JSON文件加载数据到字典2中
with open('file2.json', 'r') as f2:
dict2 = json.load(f2)
# 创建一个空字典用于存储相同key的value
common_dict = {}
# 比较两个字典中相同key的value,并将结果保存到common_dict中
for key in dict1:
if key in dict2 and dict1[key] == dict2[key]:
common_dict[key] = dict1[key]
# 根据条件判断将common_dict保存到第三个JSON文件中
with open('file3.json', 'w') as f3:
if common_dict and len(common_dict) > 2:
# 定义JSON文件格式
json_data = {
"common_keys": common_dict
}
json.dump(json_data, f3)
在此示例中,我们首先加载两个JSON文件并将它们转换为Python中的字典类型。我们创建一个空字典(common_dict),用于存储两个字典中相同key的value。我们使用for循环迭代字典1中的每个key,并检查该key是否存在于字典2中。如果存在,并且两个字典中的value相等,则将该key和对应的value添加到common_dict中。
最后,我们根据条件检查common_dict,并将其保存到第三个JSON文件(file3.json)中。实际应用中,可以根据需要更改条件和文件名。