将索引或id值添加到JSON

hmae6n7t  于 2023-10-21  发布在  其他
关注(0)|答案(3)|浏览(100)

我有一个类似这样的JSON文件:

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

我需要使用Python通过为每个数据块添加渐进的“index”/“id”来转换它。这是所需的输出(请注意,“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"
}

如果可能有用的话,我使用这里的代码通过转换CSV来构建这个JSON:https://stackoverflow.com/a/66071962/4712710

cu6pst1q

cu6pst1q1#

下面是一个使用enumerate()向每个字典添加新键的示例:

import json

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

data = json.loads(original_json_text)

data = [{"id": i, **d} for i, d in enumerate(data)]

print(json.dumps(data, indent=4, sort_keys=False))

图纸:

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

u5i3ibmn2#

完整的例子,有一些评论:

import json

# with open is important to close the file regardless of result 
with open('my_file.json') as f:
    # here we read the file and use json module to unpack
    content = json.loads(f.read())

# list comprehension, merge 2 dictionaries and enumerate, you can read more about those)
content = [{"id": index, **obj} for index, obj in enumerate(content)]
a1o7rhls

a1o7rhls3#

您可以使用JSON库相当简单地做到这一点。

import json

json_array = json.loads('''
    [
        {
            "Name": "a1",
            "Notes": "b1",
            "Active": "c1"
        },
        {
            "Name": "a2",
            "Notes": "b2",
            "Active": "c2"
        },
        {
            "Name": "a3",
            "Notes": "b4",
            "Active": "c3"
        }
    ]
''')

for i, d in enumerate(json_array):
    d["id"] = i

print(json.dumps(json_array))

这将把json代码解析成一个python对象,然后遍历数组并添加id字段。

相关问题