Sub topic 11
Converting between CSV and JSON
CSV and JSON both store records, but they model data differently. CSV is a flat grid of text. JSON is a tree of typed values. Converting between them means bridging that gap in both directions. This chapter covers the conversion code, the type problems, and the edge cases that break naive converters.
This chapter assumes you can use json.load and json.dump, csv.DictReader and csv.DictWriter, and the with statement. You should also know why CSV values arrive as strings and how to open CSV files with newline="" and an explicit encoding.
How the two formats differ
Before writing code, compare what each format can express.
| Property | CSV | JSON |
|---|---|---|
| Structure | Rows and columns (flat) | Nested objects and arrays |
| Types | Text only | string, number, boolean, null, array, object |
| Column names | Optional header row | Keys in every object |
| Missing values | Empty string or short row | `null` or an absent key |
| Record order | Row order | Array order (object key order is by convention only) |
Two consequences follow from this table.
- CSV to JSON adds information. You must decide what each text field means, and convert it to a number, boolean, or
None. - JSON to CSV loses information. Nested values and types have no direct home in a grid, so you must flatten or encode them.
CSV to JSON
The basic conversion reads each row as a dictionary and writes the list of dictionaries as a JSON array.
import csv
import json
with open("items.csv", "w", newline="", encoding="utf-8") as f:
f.write("name,qty\napple,3\n\"pear, green\",5\n")
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 first block only creates sample input so the example runs on its own. The comprehension does the real work: it names each field and converts qty with int(). Without that call, the output would contain "qty": "3", a string, and any program reading the JSON would see text where it expects a number.
Skipping the type conversion is a bug
DictReader never guesses types. If you write dict(row) straight to JSON, every value becomes a JSON string. This is valid JSON, so no error appears. The problem surfaces later, when a consumer sorts "10" before "9" or fails to add two quantities.
A reusable converter with a schema
Hard-coding every field does not scale. A small table of converter functions keeps the logic in one place and works for any file.
import csv
import json
from datetime import date
def to_bool(text):
value = text.strip().lower()
if value in ("true", "yes", "1"):
return True
if value in ("false", "no", "0"):
return False
raise ValueError(f"not a boolean: {text!r}")
def to_date(text):
return date.fromisoformat(text).isoformat()
SCHEMA = {
"name": str,
"qty": int,
"price": float,
"in_stock": to_bool,
"added": to_date,
}
def convert_row(row, schema):
result = {}
for key, text in row.items():
convert = schema.get(key, str)
if text == "":
result[key] = None
else:
result[key] = convert(text)
return result
def csv_to_json(csv_path, json_path, schema):
with open(csv_path, newline="", encoding="utf-8") as f:
rows = [convert_row(row, schema) for row in csv.DictReader(f)]
with open(json_path, "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2, ensure_ascii=False)
return len(rows)
with open("stock.csv", "w", newline="", encoding="utf-8") as f:
f.write("name,qty,price,in_stock,added\n")
f.write("apple,3,0.5,yes,2026-11-01\n")
f.write("pear,,0.75,no,2026-11-20\n")
print(csv_to_json("stock.csv", "stock.json", SCHEMA), "rows written")The output file contains "qty": null for the pear, because the empty field became None. Dates become ISO 8601 strings, since JSON has no date type.
Decide how to treat an empty field and write it down. Turning "" into null is a common choice, but a text column may legitimately hold an empty string. The converter above applies one rule to every column. If your data needs a different rule for some columns, add it to the schema functions instead.
Reporting which row failed
A bad value such as qty=abc raises ValueError with a message that does not say where it happened. Wrap the conversion and add the row number.
import csv
def convert_all(path, schema):
rows = []
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for number, row in enumerate(reader, start=2): # line 1 is the header
try:
rows.append(convert_row(row, schema))
except ValueError as exc:
raise ValueError(f"line {number}: {exc}") from exc
return rowsThis uses convert_row and SCHEMA from the previous example. The row number is an approximation: it equals the file line only when no field contains an embedded newline. reader.line_num gives the true line count of the underlying file and is the safer choice when quoted fields can span lines.
JSON to CSV
The reverse direction needs three decisions: which columns to write, how to treat missing keys, and what to do with nested values.
Flat records
For a list of flat objects, DictWriter is a direct fit.
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)DictWriter needs fieldnames because a dictionary does not say which keys form the header or in what order. If a record contains a key that is not in fieldnames, DictWriter raises ValueError. If a record lacks a key, it writes the restval value, which is an empty string by default.
Records with different keys
JSON arrays often hold objects with different keys. Taking the keys from the first record silently fails or raises on later ones. Collect the union of all keys instead, preserving first-seen order.
import csv
import json
records = [
{"id": 1, "name": "Ada"},
{"id": 2, "name": "Linus", "email": "[email protected]"},
{"id": 3, "email": "[email protected]"},
]
def collect_fields(records):
fields = {}
for record in records:
for key in record:
fields.setdefault(key, None)
return list(fields)
fieldnames = collect_fields(records)
print(fieldnames) # ['id', 'name', 'email']
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, restval="")
writer.writeheader()
writer.writerows(records)A dictionary is used instead of a set because dictionaries keep insertion order, so the columns come out in a predictable order.
This reads the whole list into memory to scan the keys. For files too large for that, scan the file twice or agree on the column list in advance.
Nested values
CSV has no way to hold a list or an object in a cell. If you pass one to DictWriter, it writes the Python str() of the value, which is not JSON. For example, a list ["a", "b"] becomes the text ['a', 'b'] with single quotes, and a reader cannot reliably parse that back.
There are two common strategies.
- Flatten with dotted keys. Turn
{"user": {"id": 1}}into a column nameduser.id. - Encode the nested value as a JSON string in one cell, so it can be restored later.
import csv
import json
def flatten(value, prefix=""):
flat = {}
for key, item in value.items():
name = f"{prefix}{key}"
if isinstance(item, dict):
flat.update(flatten(item, prefix=f"{name}."))
elif isinstance(item, list):
flat[name] = json.dumps(item)
else:
flat[name] = item
return flat
records = [
{"id": 1, "user": {"name": "Ada", "city": "London"}, "tags": ["x", "y"]},
{"id": 2, "user": {"name": "Linus", "city": "Helsinki"}, "tags": []},
]
rows = [flatten(r) for r in records]
fieldnames = list(rows[0])
with open("flat.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
print(fieldnames) # ['id', 'user.name', 'user.city', 'tags']Objects are flattened into dotted column names, and lists are stored as JSON text. The tag list of the first record is written as ["x", "y"], which json.loads can restore. A key that already contains a dot makes the flattened names ambiguous, so check for that if your data comes from outside.
Round trips and what they lose
A round trip is a conversion in one direction followed by the reverse. It rarely returns the original data. Knowing what changes helps you decide whether the conversion is acceptable.
| Starting data | After JSON, CSV, JSON | Why |
|---|---|---|
| `42` | `"42"` unless converted | CSV stores text only |
| `None` | `""` or `None` | Depends on your empty-field rule |
| `True` | `"True"` unless converted | Booleans become text |
| `["a", "b"]` | Text, or a list if you encoded it as JSON | No list type in CSV |
| Key order | Column order | Set by `fieldnames` |
| Missing key | Empty cell, then `None` or `""` | Absent and null look the same |
If a faithful round trip matters, test it. Convert, convert back, and compare the result with the original data.
import csv
import json
def to_csv_rows(records, fieldnames):
return [
{k: (json.dumps(v) if isinstance(v, (list, dict)) else v) for k, v in r.items()}
for r in records
]
original = [{"id": 1, "tags": ["a"]}, {"id": 2, "tags": []}]
with open("rt.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["id", "tags"])
writer.writeheader()
writer.writerows(to_csv_rows(original, ["id", "tags"]))
with open("rt.csv", newline="", encoding="utf-8") as f:
restored = [
{"id": int(r["id"]), "tags": json.loads(r["tags"])}
for r in csv.DictReader(f)
]
print(restored == original) # TrueThe check passes because both directions use the same agreed rules: tags is JSON text in the CSV, and id is converted back to int.
Common errors
- All values are strings in the JSON output. You skipped type conversion. Convert each field before calling
json.dump. ValueError: dict contains fields not in fieldnames. A record has a key missing fromfieldnames. Collect the union of keys, or passextrasaction="ignore"toDictWriterto drop the extra keys deliberately.- Blank lines between rows on Windows. The CSV file was opened without
newline="". - Garbled non-ASCII text. The file was opened without an explicit encoding, so the platform default was used. Pass
encoding="utf-8"to everyopen(). - Column shifts in the output. The input rows have a different number of fields than the header.
DictReaderputs extra fields under theNonekey and fills missing ones withNone, so check for these keys when your input is untrusted. TypeError: Object of type datetime is not JSON serializable. You are writing a Python object thatjsoncannot encode. Convert it first, or use thedefaultparameter.
Choosing a conversion approach
| Situation | Approach |
|---|---|
| Known columns, known types | Schema table of converter functions |
| Flat JSON array of objects | `DictWriter` with `fieldnames` from the union of keys |
| Nested JSON | Flatten to dotted columns, or store nested values as JSON text |
| Data must survive a round trip | Keep a schema and test the round trip |
| File too large for memory | Convert row by row, as covered in the streaming chapter |
Exercise
A CSV file has the columns id,active,score. A row reads 7,true,. You convert it to JSON with json.dump(list(csv.DictReader(f)), out). What does the JSON object for that row look like, and what two changes make it {"id": 7, "active": true, "score": null}?
Show answer
The object is {"id": "7", "active": "true", "score": ""}. Every value is a string, because DictReader returns text and json.dump does not guess types. To fix it, convert each field before dumping: int(row["id"]) for id, a function that maps "true" and "false" to True and False for active, and a rule that turns an empty score into None, which json.dump writes as null.
Exercise
You call csv.DictWriter(f, fieldnames=list(records[0])) on a list of JSON objects, and it fails with ValueError on the third record. What is the likely cause, and how do you fix it so that columns appear in first-seen order and missing values are blank?
Show answer
The third record has a key that the first record lacks, so DictWriter refuses to write it. Build fieldnames from the union of all keys, keeping first-seen order, for example with fields = {}, fields.setdefault(key, None) for every key of every record, and list(fields). Then create the writer with restval="" so records that lack a key get an empty cell.