如何在FastAPI中为我上传的json文件提供索引id?

问题描述 投票:0回答:1
[
  {
    "B4": 14,
    "B5": 12
  },
  {
    "B4": 58,
    "B5": 54
  },
  {
    "B4": 26,
    "B5": 65
  }
]

我想在上传的 json 文件中创建索引 id。 json 文件如图所示。我希望它像下面这样。 [ 1:{ “B4”:14, “B5”:12 }, 2:{ “B4”:58, “B5”:54 }, 3:{ “B4”:26, “B5”:65 } ]

只是对每组进行一些计算并显示结果。

python json indexing fastapi
1个回答
0
投票

导入 JSON 文件,提取每个元素并将其添加到字典中,并以其键作为索引。将字典转换为 JSON 对象并将其写入 JSON 文件。 下面是示例代码:

import json
f = open('data.json')
data = json.load(f)
updated_data = dict()
for index, item in enumerate(data, start=1):
    updated_data[index] = item
json_object = json.dumps(updated_data)
with open("updated_data.json", "w") as outfile:
    outfile.write(json_object)

输出:

{"1": {"B4": 14, "B5": 12}, "2": {"B4": 58, "B5": 54}, "3": {"B4": 26, "B5": 65}}
© www.soinside.com 2019 - 2024. All rights reserved.