如何将Excel转JSON后的数组转换为按国家键存储院校数组的结构?
实现JSON结构转换:从对象数组到按国家分组的对象
输入的JSON是一个对象数组,每个对象中不同国家对应同一所院校,我们需要将其转换为以国家为键、对应院校数组为值的结构。下面是两种常用的实现方式:
JavaScript 实现
// 假设输入数据已解析为JS对象 const inputData = [ { "GERMANY": "Berlin University of the Arts", "FRANCE": "Berlin University of the Arts", "UK": "Berlin University of the Arts", "NETHERLANDS": "Berlin University of the Arts" }, { "GERMANY": "Dresden University of Technology", "FRANCE": "Dresden University of Technology", "UK": "Dresden University of Technology", "NETHERLANDS": "Dresden University of Technology" } ]; const result = {}; inputData.forEach(item => { Object.entries(item).forEach(([country, university]) => { if (!result[country]) { result[country] = []; } result[country].push(university); }); }); // 输出转换后的JSON console.log(JSON.stringify(result, null, 2));
Python 实现
import json # 输入的JSON数据(已解析为Python列表) input_data = [ { "GERMANY": "Berlin University of the Arts", "FRANCE": "Berlin University of the Arts", "UK": "Berlin University of the Arts", "NETHERLANDS": "Berlin University of the Arts" }, { "GERMANY": "Dresden University of Technology", "FRANCE": "Dresden University of Technology", "UK": "Dresden University of Technology", "NETHERLANDS": "Dresden University of Technology" } ] result = {} for item in input_data: for country, university in item.items(): if country not in result: result[country] = [] result[country].append(university) # 打印格式化后的JSON print(json.dumps(result, indent=2))
核心逻辑
遍历原数组中的每个对象,再逐个取出对象里的「国家-院校」键值对:
- 检查结果对象中是否已有该国家的键,没有则初始化一个空数组
- 将当前院校添加到对应国家的数组中
内容的提问来源于stack exchange,提问作者Calvin Care
相关产品推荐
相关产品推荐

