Working with JSON and CSV
Turn Python objects into files other programs can read — and read them back
json for nested, typed data and csv for flat, table-shaped data.
- explain what serialization is and why files outlive your program's memory,
- convert between Python objects and JSON text with
json.dumps/loadsand read/write files withjson.dump/load, - read and predict the Python ↔ JSON type mapping (and its sharp edges: tuples,
None, dict keys), - read and write tabular data with
csv.reader/writerand the friendliercsv.DictReader/DictWriter, - avoid the classic CSV traps — the blank-row bug, everything-is-a-string, and encoding,
- choose JSON vs CSV for a given job on purpose, not by habit.
1. Structured data and serialization
Think of your program's data like the contents of a room: furniture, boxes, cables — everything arranged and connected. To move it to another house you cannot teleport the room; you pack everything into labelled boxes (a format the movers understand), ship the boxes, then unpack at the other end to rebuild the arrangement. Serialization is packing your in-memory objects into a flat stream of text; deserialization is unpacking that text back into live objects.
Why text? Because a Python dict in memory is a tangle of pointers that only this Python process understands. A text file, by contrast, is universal — a spreadsheet, a JavaScript app, a database import tool, or a colleague's editor can all read it. JSON and CSV are two agreed-upon text formats:
- JSON (JavaScript Object Notation) stores nested, typed data: objects inside lists inside objects. It maps almost one-to-one onto Python dicts and lists, which is why it is the default language of web APIs and config files.
- CSV (Comma-Separated Values) stores a single flat table: rows and columns, like one sheet of a spreadsheet. It is compact and every spreadsheet program opens it, but it has no nesting and no types.