join.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import json
  2. def read(file: "str") -> "dict":
  3. with open(file, "r", encoding="utf-8") as fp:
  4. data = json.load(fp)
  5. fp.close()
  6. return data
  7. def save(file: "str", data):
  8. with open(file, "w", encoding="utf-8") as fp:
  9. json.dump(data, fp, ensure_ascii=False, indent=2)
  10. fp.close()
  11. def get_first(data: "dict") -> "dict":
  12. for v in data.values():
  13. return v
  14. def join(deal_data: "dict", main_data: "dict") -> "dict":
  15. for cid, city in deal_data.items():
  16. pid = cid[0:2] # pid: 2
  17. first = get_first(city)
  18. if "name" in first.keys(): # county
  19. print(
  20. f"main[{pid}][{cid}]: name={main_data[pid]['children'][cid]['name']}, children={cid}"
  21. )
  22. main_data[pid]["children"][cid]["children"] = city
  23. else:
  24. for cot_id, cot in city.items():
  25. first = get_first(cot)
  26. if "name" in first.keys(): # town
  27. print(
  28. f"main[{pid}][{cid}][{cot_id}]:"
  29. f" name={main_data[pid]['children'][cid]['children'][cot_id]['name']}, children={cot_id}"
  30. )
  31. main_data[pid]["children"][cid]["children"][cot_id]["children"] = cot
  32. else: # village
  33. for tid, town in cot.items():
  34. print(
  35. f"main[{pid}][{cid}][{cot_id}][{tid}]:"
  36. f" name={main_data[pid]['children'][cid]['children'][cot_id]['children'][tid]['name']},"
  37. f" children={tid}"
  38. )
  39. main_data[pid]["children"][cid]["children"][cot_id]["children"][tid]["children"] = town
  40. return main_data
  41. def main():
  42. main_file, deal_file = "main-1.json", "deal-1.json"
  43. all_file = "all.json"
  44. main_data, deal_data = read(main_file), read(deal_file)
  45. result = join(deal_data, main_data)
  46. save(all_file, result)
  47. if __name__ == '__main__':
  48. main()
  49. """
  50. xxx居委会
  51. xxx村村委会
  52. xx村委会
  53. xxx村民委员会
  54. """