I am calling an API and it returns JSON string. I want to convert it to CSV-format so I can save it later to database. However, JSON objects keys cause problems because there is keys missing or keys are changing. I wrote this python script but because of keys I cannot get it to work:
import json
import csv
with open('custom.json') as json_file:
data = json.load(json_file)
custom_data = data['CustomJSON']
data_file = open('data_file.csv', 'w')
csv_writer = csv.writer(data_file)
count = 0
for i in custom_data:
if count == 0:
# Writing headers of CSV file
header = i.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(i.values())
data_file.close()
How I can convert this type of JSON to CSV? Example JSON message:
{
"CustomJSON" : [
{
"id" : "1,
"name" : "Jack",
"surname" : "Bauer"
},
{
"id" : "2",
"name" : "John",
"surname" : "Smith"
"age" : "31",
"city" : "New York"
},
{
"id" : "3",
"name" : "Matt",
"surname" : "Secret"
"exception_1" : "Exception_1",
"exception_2" : "Exception_2"
"date" : "2022-02-08"
}
]
}
Should I try to loop all key-values first somehow and then later try to add data? Can anyone provide an example?