config_duplicate_1.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/01
  11. @Last Modified: 2024/04/01
  12. @Summary: Config json drop duplicate.
  13. """
  14. import json
  15. import os
  16. def read_json_file(file_path):
  17. with open(file_path, 'r', encoding='utf-8') as file:
  18. return json.load(file)
  19. def compare_leaf_nodes(node1, node2):
  20. """比较两个叶节点是否相同,不同则返回None"""
  21. if isinstance(node1, dict) and isinstance(node2, dict):
  22. # 如果两个节点都是字典,递归比较它们的值
  23. return {key: compare_leaf_nodes(node1.get(key), node2.get(key)) for key in node1}
  24. elif node1 != node2:
  25. # 如果值不同,返回None
  26. return None
  27. else:
  28. # 如果值相同,返回原值
  29. return node1
  30. def compare_json_files(file_paths):
  31. # 读取第一个JSON文件作为基准
  32. base_json = read_json_file(file_paths[0])
  33. # 创建一个字典来存储比较结果
  34. result_json = {}
  35. # 遍历剩余的文件进行比较
  36. for file_path in file_paths[1:]:
  37. # 读取当前文件
  38. current_json = read_json_file(file_path)
  39. # 比较基准JSON和当前JSON的叶节点
  40. result_json = compare_leaf_nodes(base_json, current_json)
  41. # 一旦发现不同,就跳出循环,因为我们已经得到了需要的结果
  42. if None in result_json.values():
  43. break
  44. return result_json
  45. def write_json_file(file_path, data):
  46. with open(file_path, 'w', encoding='utf-8') as file:
  47. json.dump(data, file, indent=4, ensure_ascii=False)
  48. def main():
  49. # 假设您的JSON文件都在当前目录下的一个名为'json_files'的文件夹中
  50. json_dir = './jsonFiles'
  51. file_paths = [os.path.join(json_dir, f) for f in os.listdir(json_dir) if f.endswith('.json')]
  52. # 比较这些文件
  53. result_json = compare_json_files(file_paths)
  54. # 将结果写入新的JSON文件
  55. output_file_path = './output1.json'
  56. write_json_file(output_file_path, result_json)
  57. print(f'Comparison result saved to {output_file_path}')
  58. if __name__ == '__main__':
  59. main()