CSV vs JSON

When a flat table beats nested documents, and how to convert between them safely.

Pick the right shape

CSV is a flat grid of rows and columns — perfect for tabular data exported from spreadsheets and databases. JSON expresses nested, heterogeneous structures (objects inside arrays inside objects) that CSV cannot represent without conventions.

Use CSV when…Use JSON when…
Data is a simple tableData is hierarchical / nested
Humans edit it in ExcelAn API consumes it
One type of recordMixed or optional fields

Converting safely

💡
CSV has no standard type system — everything is text. Decide explicitly whether "123" becomes a number or stays a string, or you will get silent type bugs.
import csv, json

with open('data.csv', newline='', encoding='utf-8') as f:
    rows = list(csv.DictReader(f))

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(rows, f, indent=2, ensure_ascii=False)

Going the other way (JSON → CSV) only works cleanly when every record shares the same flat keys; otherwise you must flatten nested fields into dotted column names.

FAQ

Why does my CSV have quotes everywhere?
Fields containing the delimiter, a quote, or a newline are quoted per RFC 4180. A correct parser handles this; a naive split(',') does not.
Is TSV better than CSV?
When your data contains commas, tab-separated (TSV) avoids most quoting. It is common in bioinformatics and logs.

JSON basics

Last refreshed 2026-09-17.