You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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))

核心逻辑

遍历原数组中的每个对象,再逐个取出对象里的「国家-院校」键值对:

  1. 检查结果对象中是否已有该国家的键,没有则初始化一个空数组
  2. 将当前院校添加到对应国家的数组中

内容的提问来源于stack exchange,提问作者Calvin Care

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:40:27