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

如何将JSON对象的键设置为该对象自身的属性值并批量转换?

解决方案:将JSON对象转换为以自身属性为键的映射结构

需求说明

原始JSON对象结构(单个示例):

{
    "id": 1,
    "name": "Bulbasaur",
    "type_1": "Grass",
    "type_2": "Poison",
    "primary_color": "Green",
    "height": 0.7,
    "weight": 6.9,
    "hp": 45,
    "attack": 49,
    "defense": 49,
    "speed": 45,
    "can_evolve": "TRUE",
    "evolves_from": "",
    "final_evolution": "FALSE",
    "mega_evolution": "FALSE"
}

需要将900个这类对象转换为以对象自身的id和name作为顶级键的结构,每个键对应包含剩余属性的对象数组(示例结果):

{
    "1": [
        {
            "name": "Bulbasaur",
            "type_1": "Grass",
            "type_2": "Poison",
            "primary_color": "Green",
            "height": 0.7,
            "weight": 6.9,
            "hp": 45,
            "attack": 49,
            "defense": 49,
            "speed": 45,
            "can_evolve": "TRUE",
            "evolves_from": "",
            "final_evolution": "FALSE",
            "mega_evolution": "FALSE"
        }
    ],
    "Bulbasaur": [
        {
            "id": "1",
            "type_1": "Grass",
            "type_2": "Poison",
            "primary_color": "Green",
            "height": 0.7,
            "weight": 6.9,
            "hp": 45,
            "attack": 49,
            "defense": 49,
            "speed": 45,
            "can_evolve": "TRUE",
            "evolves_from": "",
            "final_evolution": "FALSE",
            "mega_evolution": "FALSE"
        }
    ]
}

解决方案

Python实现

import json

# 读取原始JSON数组文件
with open('input.json', 'r', encoding='utf-8') as f:
    pokemon_list = json.load(f)

result = {}

for pokemon in pokemon_list:
    # 处理id作为键的条目:复制对象并移除id字段
    id_key = str(pokemon['id'])
    pokemon_without_id = pokemon.copy()
    del pokemon_without_id['id']
    result[id_key] = result.get(id_key, []) + [pokemon_without_id]
    
    # 处理name作为键的条目:复制对象并移除name字段,将id转为字符串
    name_key = pokemon['name']
    pokemon_without_name = pokemon.copy()
    del pokemon_without_name['name']
    pokemon_without_name['id'] = str(pokemon['id'])
    result[name_key] = result.get(name_key, []) + [pokemon_without_name]

# 写入结果到新文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(result, f, indent=4)

JavaScript实现(Node.js环境)

const fs = require('fs');

// 读取原始JSON数组文件
const pokemonList = JSON.parse(fs.readFileSync('input.json', 'utf8'));
const result = {};

pokemonList.forEach(pokemon => {
    // 处理id作为键
    const idKey = pokemon.id.toString();
    const pokemonWithoutId = {...pokemon};
    delete pokemonWithoutId.id;
    result[idKey] = result[idKey] ? [...result[idKey], pokemonWithoutId] : [pokemonWithoutId];

    // 处理name作为键
    const nameKey = pokemon.name;
    const pokemonWithoutName = {...pokemon};
    delete pokemonWithoutName.name;
    pokemonWithoutName.id = pokemon.id.toString();
    result[nameKey] = result[nameKey] ? [...result[nameKey], pokemonWithoutName] : [pokemonWithoutName];
});

// 写入结果文件
fs.writeFileSync('output.json', JSON.stringify(result, null, 4), 'utf8');

注意事项

  • 假设原始JSON文件内容是对象数组,若原始文件是单个对象重复,需先整理为数组格式
  • 若存在id或name重复的对象,代码会自动将其追加到对应键的数组中
  • 代码已将id转换为字符串,完全匹配示例结果的格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:30:52