如何在FastAPI中给上传的json文件添加索引ID?
[
{
"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
}
]
这样做只是为了对每一组数据进行一些计算,然后显示结果。
2 个回答
0
你分享的这个输出列表是不正确的,因为列表不能作为键值对。你是想说这个吗 - 一个字典里面再嵌套一个字典?
{
1: {
"B4": 14,
"B5": 12
},
2: {
"B4": 58,
"B5": 54
},
}
要得到这个 -
import json
with open("file/path.json") as file:
data = json.load(file) # Output a list of dict
dict_with_index = dict(zip(range(1,len(data) + 1), data))
1
首先,你需要导入你的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}}