CSV and JSON files · 5 / 15 Theory

CSV or JSON: which to choose and good practices

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

CSVJSON
Structureflat table: rows and columnsstructured data: nested objects and lists
Data typeseverything is texttexts, numbers, booleans, null, lists and objects
Opens withExcel, spreadsheetsbrowsers, APIs, code editors
Sizesmall: the header is not repeatedbigger: repeats the keys in each object
Ideal forlistings, 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="" in open and let the csv module handle the quotes and commas; do not build the lines by hand.
  • CSV: convert the values with int() or float() before calculating, because everything is read as text.
  • JSON: use indent=2 if a person is going to read the file, and ensure_ascii=False to keep the accents.
  • Both: do not assume the data is correct. Catch the errors (JSONDecodeError, ValueError when converting, KeyError for 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

ErrorCauseSolution
A field with a comma is cutusing split(",")use csv.reader
Blank lines between rowsmissing newline="" when writing on Windowsopen(..., newline="")
TypeError when addingvalues read as textconvert with int/float
Wrong accents (é)wrong encodingencoding="utf-8"
JSONDecodeErrorsingle quotes, extra comma or unclosed bracecheck the text; catch the error
not JSON serializableunsupported 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.