import json def read(file: "str") -> "dict": with open(file, "r", encoding="utf-8") as fp: data = json.load(fp) fp.close() return data def save(file: "str", data): with open(file, "w", encoding="utf-8") as fp: json.dump(data, fp, ensure_ascii=False, indent=2) fp.close() def get_first(data: "dict") -> "dict": for v in data.values(): return v def join(deal_data: "dict", main_data: "dict") -> "dict": for cid, city in deal_data.items(): pid = cid[0:2] # pid: 2 first = get_first(city) if "name" in first.keys(): # county print( f"main[{pid}][{cid}]: name={main_data[pid]['children'][cid]['name']}, children={cid}" ) main_data[pid]["children"][cid]["children"] = city else: for cot_id, cot in city.items(): first = get_first(cot) if "name" in first.keys(): # town print( f"main[{pid}][{cid}][{cot_id}]:" f" name={main_data[pid]['children'][cid]['children'][cot_id]['name']}, children={cot_id}" ) main_data[pid]["children"][cid]["children"][cot_id]["children"] = cot else: # village for tid, town in cot.items(): print( f"main[{pid}][{cid}][{cot_id}][{tid}]:" f" name={main_data[pid]['children'][cid]['children'][cot_id]['children'][tid]['name']}," f" children={tid}" ) main_data[pid]["children"][cid]["children"][cot_id]["children"][tid]["children"] = town return main_data def main(): main_file, deal_file = "main-1.json", "deal-1.json" all_file = "all.json" main_data, deal_data = read(main_file), read(deal_file) result = join(deal_data, main_data) save(all_file, result) if __name__ == '__main__': main() """ xxx居委会 xxx村村委会 xx村委会 xxx村民委员会 """