config_merge.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##################################################################
  4. #
  5. # Copyright (c) 2024 CICV, Inc. All Rights Reserved
  6. #
  7. ##################################################################
  8. """
  9. @Authors: yangzihao(yangzihao@china-icv.cn)
  10. @Data: 2024/04/22
  11. @Last Modified: 2024/04/22
  12. @Summary: Config jsons merge and process.
  13. """
  14. import json
  15. def merge_json(base_json, compare_json):
  16. # 遍历比较JSON文件的键值对
  17. for key, value in compare_json.items():
  18. # 如果基准JSON文件中不包含该键,则直接添加对应的键值对
  19. if key not in base_json:
  20. base_json[key] = value
  21. else:
  22. # 如果值是字典类型,则递归进行比较和合并
  23. if isinstance(value, dict) and isinstance(base_json[key], dict):
  24. merge_json(base_json[key], value)
  25. # 如果值是列表类型,则递归对比列表中的每个元素
  26. elif isinstance(value, list) and isinstance(base_json[key], list):
  27. for idx, item in enumerate(value):
  28. if idx < len(base_json[key]) and isinstance(item, dict):
  29. # 如果列表中的元素是字典,则递归进行比较和合并
  30. merge_json(base_json[key][idx], item)
  31. elif idx >= len(base_json[key]) and isinstance(item, dict):
  32. # 如果列表中的元素是字典,并且基准JSON中的列表不包含该元素,则添加到列表中
  33. base_json[key].append(item)
  34. else:
  35. # 对比值不同的情况,将最后一级的值设为空字符串
  36. if base_json[key] != value:
  37. if isinstance(value, dict):
  38. merge_json(base_json[key], value)
  39. else:
  40. base_json[key] = ""
  41. def compare_and_merge(base_file, *compare_files):
  42. # 读取基准JSON文件
  43. with open(base_file, 'r', encoding='utf-8') as f:
  44. base_data = json.load(f)
  45. # 遍历需要比较的JSON文件
  46. for compare_file in compare_files:
  47. with open(compare_file, 'r', encoding='utf-8') as f:
  48. compare_data = json.load(f)
  49. # 调用merge_json函数进行比较和合并
  50. merge_json(base_data, compare_data)
  51. return base_data
  52. if __name__ == '__main__':
  53. # 示例用法
  54. # merged_data = compare_and_merge('config0.json', 'config1.json', 'config2.json', 'config3.json')
  55. merged_data = compare_and_merge('config1.json', 'config2.json', 'config3.json')
  56. # print(json.dumps(merged_data, indent=4, ensure_ascii=False))
  57. with open('output123.json', 'w', encoding='utf-8') as f:
  58. f.write(json.dumps(merged_data, indent=4, ensure_ascii=False))
  59. print("over.")