Both formats serve to store data as text, but they solve different problems. Choosing the format well makes the rest of the program simpler.
When to use each one
| CSV | JSON | |
|---|---|---|
| Structure | flat table: rows and columns | structured data: nested objects and lists |
| Data types | everything is text | texts, numbers, booleans, null, lists and objects |
| Opens with | Excel, spreadsheets | browsers, APIs, code editors |
| Size | small: the header is not repeated | bigger: repeats the keys in each object |
| Ideal for | listings, exports, data from a single "table" | configuration, API responses, hierarchical data |
The same data in both formats:
# CSV
name,age
Ana,30
Luis,25
# JSON
[
{"name": "Ana", "age": 30},
{"name": "Luis", "age": 25}
]
A piece of data like "Ana has two addresses, and each address has a street and a city" does not fit well in a flat table: there JSON is the best option.
Converting from CSV to JSON
It is a very frequent operation. With DictReader and json it takes a few lines, and it is the moment to convert the texts to the right type:
import csv
import json
lines = ["name,age", "Ana,30", "Luis,25"]
people = []
for row in csv.DictReader(lines):
people.append({"name": row["name"], "age": int(row["age"])})
print(json.dumps(people))
# [{"name": "Ana", "age": 30}, {"name": "Luis", "age": 25}]
Good practices
- Encoding: always open files with
encoding="utf-8"so that accents andñwork on any system. - CSV: use
newline=""inopenand let thecsvmodule handle the quotes and commas; do not build the lines by hand. - CSV: convert the values with
int()orfloat()before calculating, because everything is read as text. - JSON: use
indent=2if a person is going to read the file, andensure_ascii=Falseto keep the accents. - Both: do not assume the data is correct. Catch the errors (
JSONDecodeError,ValueErrorwhen converting,KeyErrorfor missing columns) and warn with a clear message. - External data: if the file was given to you by another person or program, check that it has the columns and keys you expect before using it.
Common mistakes
| Error | Cause | Solution |
|---|---|---|
| A field with a comma is cut | using split(",") | use csv.reader |
| Blank lines between rows | missing newline="" when writing on Windows | open(..., newline="") |
TypeError when adding | values read as text | convert with int/float |
Wrong accents (é) | wrong encoding | encoding="utf-8" |
JSONDecodeError | single quotes, extra comma or unclosed brace | check the text; catch the error |
not JSON serializable | unsupported type (set, date) | convert it first to a list or text |
And to remember what happens in each format, review Order total and From CSV to JSON.