1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- ##################################################################
- #
- # Copyright (c) 2024 CICV, Inc. All Rights Reserved
- #
- ##################################################################
- """
- @Authors: yangzihao(yangzihao@china-icv.cn)
- @Data: 2024/04/22
- @Last Modified: 2024/04/22
- @Summary: Config jsons merge and process.
- """
- import json
- def merge_json(base_json, compare_json):
- # 遍历比较JSON文件的键值对
- for key, value in compare_json.items():
- # 如果基准JSON文件中不包含该键,则直接添加对应的键值对
- if key not in base_json:
- base_json[key] = value
- else:
- # 如果值是字典类型,则递归进行比较和合并
- if isinstance(value, dict) and isinstance(base_json[key], dict):
- merge_json(base_json[key], value)
- # 如果值是列表类型,则递归对比列表中的每个元素
- elif isinstance(value, list) and isinstance(base_json[key], list):
- for idx, item in enumerate(value):
- if idx < len(base_json[key]) and isinstance(item, dict):
- # 如果列表中的元素是字典,则递归进行比较和合并
- merge_json(base_json[key][idx], item)
- elif idx >= len(base_json[key]) and isinstance(item, dict):
- # 如果列表中的元素是字典,并且基准JSON中的列表不包含该元素,则添加到列表中
- base_json[key].append(item)
- else:
- # 对比值不同的情况,将最后一级的值设为空字符串
- if base_json[key] != value:
- if isinstance(value, dict):
- merge_json(base_json[key], value)
- else:
- base_json[key] = ""
- def compare_and_merge(base_file, *compare_files):
- # 读取基准JSON文件
- with open(base_file, 'r', encoding='utf-8') as f:
- base_data = json.load(f)
- # 遍历需要比较的JSON文件
- for compare_file in compare_files:
- with open(compare_file, 'r', encoding='utf-8') as f:
- compare_data = json.load(f)
- # 调用merge_json函数进行比较和合并
- merge_json(base_data, compare_data)
- return base_data
- if __name__ == '__main__':
- # 示例用法
- # merged_data = compare_and_merge('config0.json', 'config1.json', 'config2.json', 'config3.json')
- # merged_data = compare_and_merge('config1.json', 'config2.json', 'config3.json')
- # merged_data = compare_and_merge('config1.json', 'config2.json')
- # merged_data = compare_and_merge('config1.json', 'config3.json')
- merged_data = compare_and_merge('config2.json', 'config3.json')
- # merged_data = compare_and_merge('config0.json', 'config1.json')
- # merged_data = compare_and_merge('config0.json', 'config2.json')
- # merged_data = compare_and_merge('config0.json', 'config3.json')
- # print(json.dumps(merged_data, indent=4, ensure_ascii=False))
- with open('config23.json', 'w', encoding='utf-8') as f:
- f.write(json.dumps(merged_data, indent=4, ensure_ascii=False))
- print("over.")
|