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

如何将JSON对象转换为数组并添加对象位置信息

JSON结构转换及位置信息添加方案

问题描述

原始JSON结构:

{
    "key": 111,
    "Students":{
       "AddressInfo":{
         
       }
    }
}

需要完成两个操作:

  1. 将Students字段的单个对象转换为数组形式,目标结构:
{
    "key": 111,
    "Students":[
       {
       "AddressInfo":{

       }
      }
    ]
}
  1. 在数组内的对象中添加位置信息(标记元素在数组中的位置)。

实现方案

1. 单个对象转数组

核心逻辑是把Students对应的对象包装进数组,以下是两种常用语言的实现:

JavaScript

const original = {
    "key": 111,
    "Students": { "AddressInfo": {} }
};

// 转换为数组
original.Students = [original.Students];
console.log(JSON.stringify(original, null, 2));

Python

import json

original = {
    "key": 111,
    "Students": { "AddressInfo": {} }
}

original["Students"] = [original["Students"]]
print(json.dumps(original, indent=2))

2. 添加位置信息

以给数组元素添加position字段标记索引为例:

JavaScript

const original = {
    "key": 111,
    "Students": { "AddressInfo": {} }
};

// 转数组并添加位置信息
original.Students = [
    {
        ...original.Students,
        "position": 0 // 多元素场景可通过循环批量赋值索引
    }
];
console.log(JSON.stringify(original, null, 2));

Python

import json

original = {
    "key": 111,
    "Students": { "AddressInfo": {} }
}

student = original["Students"]
student["position"] = 0
original["Students"] = [student]
print(json.dumps(original, indent=2))

执行后得到的最终结构:

{
  "key": 111,
  "Students": [
    {
      "AddressInfo": {},
      "position": 0
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:57:38