JSON to CSV Converter
Quickly transform a JSON array of objects into a CSV file using Python.
Sometimes you need to convert an API response or dataset from JSON into a spreadsheet‑friendly format. This Python script reads a JSON file containing an array of objects, determines the field names, and writes them to a CSV file. It uses the built‑in json
and csv
modules—no external dependencies required.
import json
import csv
from pathlib import Path
def json_to_csv(json_path: str, csv_path: str) -> None:
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if not data:
return
keys = sorted({k for item in data for k in item.keys()})
with open(csv_path, 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=keys)
writer.writeheader()
writer.writerows(data)
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print("Usage: python json_to_csv.py input.json output.csv")
sys.exit(1)
json_to_csv(sys.argv[1], sys.argv[2])
Run this script from the command line: python json_to_csv.py data.json data.csv
. It produces a CSV file with all object keys as columns. Modify it to suit nested structures or specific field ordering.