json_merge.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import argparse
  16. def json_merge(json1_path, json2_path, save_path, merge_keys):
  17. print("Merge".center(100, "-"))
  18. print("json read...\n")
  19. with open(json1_path, "r") as load_f:
  20. data1 = json.load(load_f)
  21. with open(json2_path, "r") as load_f:
  22. data2 = json.load(load_f)
  23. print("json merge...")
  24. data = {}
  25. for k, v in data1.items():
  26. if k not in merge_keys:
  27. data[k] = v
  28. print(k)
  29. else:
  30. data[k] = data1[k] + data2[k]
  31. print(k, "merge!")
  32. print()
  33. print("json save...\n")
  34. data_str = json.dumps(data, ensure_ascii=False)
  35. with open(save_path, "w", encoding="utf-8") as save_f:
  36. save_f.write(data_str)
  37. if __name__ == "__main__":
  38. parser = argparse.ArgumentParser(description="Merge JSON files")
  39. parser.add_argument("--json1_path", type=str, required=True, \
  40. help="Path of the first JSON file to merge.")
  41. parser.add_argument("--json2_path", type=str, required=True, \
  42. help="Path of the second JSON file to merge.")
  43. parser.add_argument("--save_path", type=str, required=True, \
  44. help="Path to save the merged JSON file.")
  45. parser.add_argument("--merge_keys", type=list, default=["images", "annotations"], \
  46. help="Keys to be merged.")
  47. args = parser.parse_args()
  48. json_merge(args.json1_path, args.json2_path, args.save_path,
  49. args.merge_keys)