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

如何用Python为JSON数据块添加递增id字段?

为JSON对象添加递增id字段的Python实现

需求说明

现有如下格式的JSON数据(注:原始数据为多个独立JSON对象,需先包裹为合法数组才能正常解析):

{
    "Name": "a1",
    "Notes": "b1",
    "Active": "c1"
},
{
    "Name": "a2",
    "Notes": "b2",
    "Active": "c2"
},
{
    "Name": "a3",
    "Notes": "b4",
    "Active": "c3"
}

需要为每个对象添加无引号数字类型的递增id字段,最终输出如下:

{
    "id": 0,
    "Name": "a1",
    "Notes": "b1",
    "Active": "c1"
},
{
    "id": 1,
    "Name": "a2",
    "Notes": "b2",
    "Active": "c2"
},
{
    "id": 2,
    "Name": "a3",
    "Notes": "b4",
    "Active": "c3"
}

Python实现代码

import json

# 先将原始JSON片段包裹为合法数组
raw_json = """
[
    {
        "Name": "a1",
        "Notes": "b1",
        "Active": "c1"
    },
    {
        "Name": "a2",
        "Notes": "b2",
        "Active": "c2"
    },
    {
        "Name": "a3",
        "Notes": "b4",
        "Active": "c3"
    }
]
"""

# 解析JSON为Python列表
data_list = json.loads(raw_json)

# 遍历列表,为每个对象添加数字类型的id字段
for index, item in enumerate(data_list):
    item["id"] = index

# 转换回JSON字符串,格式化输出
formatted_json = json.dumps(data_list, indent=4)

# 去掉数组首尾的[],得到需求中的对象分隔格式
print(formatted_json[1:-1])

代码说明

  1. 合法性处理:原始输入的JSON片段不是合法数组结构,必须先包裹在[]中,否则无法用json.loads正常解析。
  2. 添加id字段:使用enumerate遍历列表,同时获取索引和对象元素,直接为元素添加id键,值为索引(天然是数字类型,满足无引号要求)。
  3. 输出格式调整:如果需要保留数组格式,直接打印formatted_json即可;若要得到需求中多个独立对象分隔的格式,截取字符串去掉首尾的[]即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:09:58