I have .json files in the following format:
{
"uls":{
"equ1-L1-u": {"D": 1.10, "La": 1.50, "Lb": 1.50},
"equ1-L2-u": {"D": 1.10, "La": 1.50, "Lb": 1.50},
},
"sls":{
"cha-L1": {"Ld": 1.00, "Le": 1.00, "Lf": 1.00, "Lg": 1.00, "Lh": 1.00},
"cha-L2": {"D": 1.00, "Df": 1.00},
}
}
which I want to convert to CSV “database” style format:
Criteria, Name, D, Df, La, Lb, Ld, Le, Lf, Lg, Lh
uls, equ1-L1-u, 1.10, , 1.50, 1.50, , , , ,
uls, equ1-L2-u, 1.10, , 1.50, 1.50, , , , ,
sls, cha-L1, , , , ,1.00 , 1.00, 1.00, 1.00, 1.00
sls, cha-L2, 1.00, 1.00, , , , , , ,
Ideally, I would not have to define the value keys beforehand, but for now I’m fine doing it if needed.
Here’s what I got now, it’s working for this specific case of 2 level of nesting. I’m able to do make it work for 3 or 4 levels of nesting by modifying the code, but ideally the same code could be used for all levels of nesting (maybe recursion?).
# Function to convert json objects to csv
import json
import csv
def make_csv_dict(data, key_headers):
csv_dict = []
for i in data:
for j in data[i]:
csv_dict.append({
key_headers[0]: i,
key_headers[1]: j,
**data[i][j]
})
return csv_dict
### ENTER DATA HERE ###
key_headers = ["Criteria", "Name"]
path = "File.json"
### ENTER DATA HERE ###
# Read json
with open(path) as json_file:
data = json.load(json_file)
# make csv_dict from .json data
csv_dict = make_csv_dict(data, key_headers)
# writing to csv file
fieldnames = ["Criteria", "Name", "D", "Df", "La", "Lb", "Lc", "Ld", "Le", "Lf", "Lg", "Lh", "Sl", "Sh", "W", "T", "A", "E"]
with open(path.replace(".json",".csv"), 'w', newline="") as f:
writer = csv.DictWriter(f, fieldnames)
writer.writeheader()
writer.writerows(csv_dict)