Convert JSON to CSV
Convert a JSON array of objects to a CSV file.
Code
Python
import csv
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
if data:
with open("output.csv", "w", encoding="utf-8", newline="") as out:
writer = csv.DictWriter(out, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)Line-by-line explanation
- 1.Load JSON data from file.
- 2.Check that the list is non-empty.
- 3.Use csv.DictWriter with keys from the first object as fieldnames.
- 4.Write the header row, then all data rows.
Expected output
output.csv created