How to give index id to my uploaded json file in FastAPI?

66 views Asked by At
[
  {
    "B4": 14,
    "B5": 12
  },
  {
    "B4": 58,
    "B5": 54
  },
  {
    "B4": 26,
    "B5": 65
  }
]

I want to create index ID in my uploaded json file. The json file look like as in the image. I want it to be like the following:

[
  1: {
       "B4": 14,
       "B5": 12
     },
  2: {
       "B4": 58,
       "B5": 54
     },
  3: {
       "B4": 26,
       "B5": 65
     }
]

It's just to do some calculations for each set and display the results.

2

There are 2 answers

0
Ammar On BEST ANSWER

Import your JSON file, extract each element and add it to a dictionary with its key as index. Convert the dictionary to a JSON object and write it on to a JSON file. Here is the sample code below:

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)

Output:

{"1": {"B4": 14, "B5": 12}, "2": {"B4": 58, "B5": 54}, "3": {"B4": 26, "B5": 65}}
0
Sowmya On

The list you shared as output is not valid as list cannot be a key value pair. Did you mean this - a dict of dicts?

{
  1: {
       "B4": 14,
       "B5": 12
     },
  2: {
       "B4": 58,
       "B5": 54
     },
}

To get that -

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))