Sub topic 11
Converting between CSV and JSON
This chapter assumes you can open files with with, use dicts and lists, and catch exceptions. It also assumes you know csv.DictReader, csv.DictWriter, json.load, and json.dump from earlier chapters. Here you combine them to move data between the two formats in both directions.
Why conversion needs care
CSV and JSON describe data differently.
- CSV is a flat table. Every value is a string, and every row has the same columns.
- JSON has types (numbers, booleans,
null) and can nest lists and objects inside each other.
Two problems follow from this. Going from CSV to JSON, you must convert strings to proper types, or your numbers will be written as "3" instead of 3. Going from JSON to CSV, you can only write data that is flat, so you must decide what to do with nested values.
CSV to JSON
Suppose items.csv contains this:
name,qty
apple,3
"pear, green",5DictReader yields one dict per row. Convert qty to an int before you store it.
import csv
import json
with open("items.csv", newline="", encoding="utf-8") as f:
items = [{"name": r["name"], "qty": int(r["qty"])} for r in csv.DictReader(f)]
with open("items.json", "w", encoding="utf-8") as f:
json.dump(items, f, indent=2)The output is a list of objects with qty as a real number:
[
{
"name": "apple",
"qty": 3
},
{
"name": "pear, green",
"qty": 5
}
]The file is opened with newline="" and an explicit encoding, as in the earlier chapters. Leaving those out is a common source of blank lines and garbled characters.
Handling bad values
int("") and int("n/a") raise ValueError. Real files often have empty cells, so decide on a policy. One option is to store None, which becomes null in JSON.
def to_int(text):
text = text.strip()
return int(text) if text else NoneJSON to CSV
A JSON list of flat objects maps directly onto DictWriter. You must pass fieldnames yourself, because a dict has no required key order or complete key set.
import csv
import json
with open("items.json", encoding="utf-8") as f:
items = json.load(f)
with open("items_out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "qty"])
writer.writeheader()
writer.writerows(items)Records with different keys
DictWriter behaves in two ways you should know about:
- A missing key is written as an empty field. You can change this with
restval. - An extra key raises
ValueError. Passextrasaction="ignore"to drop extras, or buildfieldnamesfrom all keys.
The second approach collects every key across the records and keeps first-seen order:
import csv
import json
records = json.loads('[{"id": 1, "tag": "a"}, {"id": 2, "note": "x"}]')
fieldnames = []
for record in records:
for key in record:
if key not in fieldnames:
fieldnames.append(key)
with open("merged.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, restval="")
writer.writeheader()
writer.writerows(records)This writes the columns id, tag, and note, and leaves empty cells where a record lacks a key.
Flattening nested data
CSV cannot hold a list or a dict in a cell. If you pass one, DictWriter writes its Python str() form, such as ['a', 'b'], which is hard to read back. Flatten first. Two simple options are joining a list into one string, or turning nested keys into dotted column names.
def flatten(record, prefix=""):
flat = {}
for key, value in record.items():
name = f"{prefix}{key}"
if isinstance(value, dict):
flat.update(flatten(value, prefix=f"{name}."))
elif isinstance(value, list):
flat[name] = ";".join(str(v) for v in value)
else:
flat[name] = value
return flat
print(flatten({"id": 1, "user": {"name": "Ada"}, "tags": ["x", "y"]}))
# {'id': 1, 'user.name': 'Ada', 'tags': 'x;y'}Flattening loses structure. A round trip from nested JSON to CSV and back will not give you the original unless you write code to rebuild it.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Numbers appear in quotes in JSON | CSV values were not converted | Convert with `int()` or `float()` before dumping |
| `ValueError: dict contains fields not in fieldnames` | A record has a key missing from `fieldnames` | Build `fieldnames` from all keys, or use `extrasaction="ignore"` |
| Blank line between CSV rows on Windows | File opened without `newline=""` | Always pass `newline=""` |
| Cells contain `['a', 'b']` | Nested list written directly | Flatten before writing |
| `null` becomes an empty string, then back as `""` | CSV has no null | Choose one convention and apply it on both sides |
Exercise
A JSON file holds a list of objects like {"id": 1, "price": 2.5}. You write it to CSV with DictWriter, then read the CSV with DictReader. What is the type of row["price"], and what must you do to get a number back?
Show answer
It is a str, because the csv module returns every value as a string. Convert it with float(row["price"]) after reading.
Exercise
Why does csv.DictWriter raise ValueError when a record contains a key that is not in fieldnames, and how can you avoid the error without losing the other columns?
Show answer
DictWriter has no column to put the extra value in. Either pass extrasaction="ignore" to drop the extra key, or build fieldnames from the union of all keys in the records so every key gets a column.