config_duplicate.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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_json_files(file_paths):
  20. # 读取第一个JSON文件作为基准
  21. base_json = read_json_file(file_paths[0])
  22. # 创建一个字典来存储比较结果
  23. result_json = {}
  24. # 遍历基准JSON的所有key
  25. for key in base_json:
  26. # 初始化所有文件的该key的值为基准值
  27. result_value = base_json[key]
  28. # 遍历剩余的文件进行比较
  29. for file_path in file_paths[1:]:
  30. # 读取当前文件
  31. current_json = read_json_file(file_path)
  32. # 检查key是否存在,并且值是否相同
  33. if key not in current_json or current_json[key] != result_value:
  34. # 如果不同,则将该key的值设为null
  35. result_value = None
  36. break
  37. # 将最终值添加到结果JSON中
  38. result_json[key] = result_value
  39. return result_json
  40. def write_json_file(file_path, data):
  41. with open(file_path, 'w', encoding='utf-8') as file:
  42. json.dump(data, file, ensure_ascii=False, indent=4)
  43. def main():
  44. # 假设您的JSON文件都在当前目录下的一个名为'json_files'的文件夹中
  45. json_dir = './jsonFiles'
  46. file_paths = [os.path.join(json_dir, f) for f in os.listdir(json_dir) if f.endswith('.json')]
  47. # 比较这些文件
  48. result_json = compare_json_files(file_paths)
  49. # 将结果写入新的JSON文件
  50. output_file_path = './output.json'
  51. write_json_file(output_file_path, result_json)
  52. print(f'Comparison result saved to {output_file_path}')
  53. if __name__ == '__main__':
  54. main()