这个想法是:
- 用于
json.load()
将JSON内容从文件加载到Python列表 id
使用collections.defaultdict
和.update()
方法将数据重新分组- 用于
json.dump()
将结果转储到JSON文件中
实现方式:
import jsonfrom collections import defaultdict# read JSON datawith open("input.json") as input_file: old_data = json.load(input_file)# regroup datad = defaultdict(dict)for item in old_data: d[item["id"]].update(item)# write JSON datawith open("output.json", "w") as output_file: json.dump(list(d.values()), output_file, indent=4)现在,
output.json将包含:
[ { "d": 66, "e": 44, "a": 22, "b": 11, "c": 77, "id": 1, "f": 55 }, { "b": 11, "id": 3, "d": 44, "c": 88, "a": 22 }]


