I’ve got a JSON file similar to this:
{
"Name": "a1",
"Notes": "b1",
"Active": "c1"
},
{
"Name": "a2",
"Notes": "b2",
"Active": "c2"
},
{
"Name": "a3",
"Notes": "b4",
"Active": "c3"
}
I need to transform it using Python by adding a progressive "index"/"id" for every data block.
This is the desired output (notice that there are no quotes around the "id" value):
{
"id": 0,
"Name": "a1",
"Notes": "b1",
"Active": "c1"
},
{
"id": 1,
"Name": "a2",
"Notes": "b2",
"Active": "c2"
},
{
"id": 2,
"Name": "a3",
"Notes": "b4",
"Active": "c3"
}
If it might be useful I’m building this JSON by converting a CSV using the code found here: https://stackoverflow.com/a/66071962/4712710
3
Answers
Here is an example how you can add new keys to each dictionary using
enumerate()
:Prints:
You can do this fairly simply with the JSON library.
This parses the json code into a python object, and then iterates through the array and adds the id field.
Full example, with some comments: