I am trying to add a top-level element to a JSON output that I get from an API.
The following example shows the JSON output that I get from the API:
[{
"Id": 1,
"FirstName": "Ken",
"LastName": "Sánchez",
"Info": {
"MiddleName": "J"
}
}, {
"Id": 2,
"FirstName": "Terri",
"LastName": "Duffy",
"Info": {
"MiddleName": "Lee"
}
}, {
"Id": 3,
"FirstName": "Roberto",
"LastName": "Tamburello"
}, {
"Id": 4,
"FirstName": "Rob",
"LastName": "Walters"
}, {
"Id": 5,
"FirstName": "Gail",
"LastName": "Erickson",
"Info": {
"Title": "Ms.",
"MiddleName": "A"
}
}]
And the following example shows the desired JSON output that contains the root element "info":
{
"info": [{
"Id": 1,
"FirstName": "Ken",
"LastName": "Sánchez",
"Info": {
"MiddleName": "J"
}
}, {
"Id": 2,
"FirstName": "Terri",
"LastName": "Duffy",
"Info": {
"MiddleName": "Lee"
}
}, {
"Id": 3,
"FirstName": "Roberto",
"LastName": "Tamburello"
}, {
"Id": 4,
"FirstName": "Rob",
"LastName": "Walters"
}, {
"Id": 5,
"FirstName": "Gail",
"LastName": "Erickson",
"Info": {
"Title": "Ms.",
"MiddleName": "A"
}
}]
}
I tried to append it, however, this is included as another element at the end of each array.
Could someone give me a hint on this?
I also tried with the following code, but breaks the json format
with open(file_name, 'w') as f:
data2= '{"info":'+str(data)+'}]'
json.dump(data2, f)
Thanks!