I am new to python and I would like to convert below Json file to CSV file by using python. Please don't pass the whole json data in the code. Just pass the whole Json file in the code.
{
"Breakfast": {
"Brk_item1": "Milk",
"Brk_item2": "Egg"
},
"Lunch": {
"Lnc_item1": "Pasta",
"Lnc_item2": "Sprouts"
},
"Dinner": {
"Dnr_item1": "Pizza",
"Dnr_item2": "Burger"
}
},
{
"Breakfast": {
"Brk_item1": "Bread",
"Brk_item2": "Butter"
},
"Lunch": {
"Lnc_item1": "Indian Meal",
"Lnc_item2": "Paratha"
},
"Dinner": {
"Dnr_item1": "Roti",
"Dnr_item2": "Paneer"
}
}
and my expected output will be like below in CSV format
Brk_item1 Brk_item2 Lnc_item1 Lnc_item2 Dnr_item1 Dnr_item2
Milk Egg Pasta Sprouts Pizza Burger
Bread Butter Indian Meal Paratha Roti Paneer
This is what I have tried so far:
import json
import csv
with open("./sample.json") as file:
data = json.load(file)
fname="output.csv"
with open(fname,"w") as file:
csv_file = csv.writer(file)
csv_file.writerow ([ "Brk_item1","Brk_item2","Lnc_item1","Lnc_item2","Dnr_item1","Dnr_item2"])
for item in data["Breakfast"]:
csv_file.writerow([item["Brk_item1"],item["Brk_item2"],item["Lnc_item1"],item["Lnc_item2"],item["Dnr_item1"],item["Dnr_item2"]])
The first step is writting the header of file (you did it correctly).
csv_file = csv.writer(file)
csv_file.writerow (["Brk_item1","Brk_item2","Lnc_item1","Lnc_item2","Dnr_item1","Dnr_item2"])
If your loaded json array, it's an array of dicts, the next step is iterate the array elements for elem in data
. So, in this step, each elem is a dict which has 3 elements: Breakfast
, Lunch
, Dinner
. There all multiple ways to append the values, but as the element names of dicts are all different, and just are 3 elements and they are always the same, the easy way is to hardcode the values.
fname="output.csv"
with open(fname,"w") as file:
csv_file = csv.writer(file)
csv_file.writerow (["Brk_item1","Brk_item2","Lnc_item1","Lnc_item2","Dnr_item1","Dnr_item2"])
for elem in data:
csv_file.writerow([elem['Breakfast']['Brk_item1'],elem['Breakfast']['Brk_item2'],elem['Lunch']['Lnc_item1'], elem['Lunch']['Lnc_item2'], elem['Dinner']['Dnr_item1'],elem['Dinner']['Dnr_item2']])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.