Short answer: JSON converts cleanly to CSV when it is an array of flat objects — each object becomes a row, each key becomes a column. In Python it is ten lines with the csv module, and on the command line it is a single jq invocation. The only real work is nested data, which CSV cannot represent directly.
The shape that converts cleanly
CSV is two-dimensional: rows and columns, nothing else. The JSON shape that maps onto it without decisions is an array of objects with the same flat keys:
[
{ "id": 1, "name": "Alice", "role": "admin" },
{ "id": 2, "name": "Bob", "role": "editor" }
]
// becomes:
// id,name,role
// 1,Alice,admin
// 2,Bob,editorEverything difficult about this conversion lives in the gap between that ideal shape and real JSON. Real API responses nest objects inside objects, hide arrays inside records, and let different records carry different keys. None of that makes conversion impossible — it makes it a set of decisions instead of a single command. The sections below are those decisions, in the order you will meet them: flatten or not, which columns exist, and what to do with lists.
Python: csv.DictWriter
For flat records, the standard library is all you need. This assumes the data is a list of dicts with uniform keys:
import json, csv
with open("data.json") as f:
data = json.load(f)
with open("out.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)When records do not share the same keys
The snippet above trusts the first record to name every column, and real data breaks that trust quietly: if record one lacks a field that record forty has, that field never becomes a column and its values vanish without an error. The robust version collects the union of all keys first, in first-seen order, and hands that to the writer. Missing values then become empty cells — which is the truth about the data — instead of disappearing entirely:
fieldnames = []
for row in data:
for key in row:
if key not in fieldnames:
fieldnames.append(key)
writer = csv.DictWriter(f, fieldnames=fieldnames, restval="")
writer.writeheader()
writer.writerows(data)Nested data: pandas json_normalize
When objects contain objects, flatten them first. json_normalize turns nested keys into dot-notation columns:
import pandas as pd
data = [
{"id": 1, "user": {"name": "Alice", "city": "NYC"}},
{"id": 2, "user": {"name": "Bob", "city": "SF"}},
]
df = pd.json_normalize(data, sep=".")
df.to_csv("out.csv", index=False)
# id,user.name,user.city
# 1,Alice,NYC
# 2,Bob,SFArrays inside records: join or explode
Flattening handles nested objects; arrays need a different decision, because a cell cannot hold a list. You have exactly two honest options. Join the values into one cell with a separator that is not a comma — tags: ["a", "b"] becomes a|b — which keeps one row per record and is right when the list is a property of the record, like tags or categories. Or explode the array into multiple rows, one per element, repeating the record's other values on each row — right when each element is really its own fact, like one row per item in an order. What you must not do is let a tool silently stringify the array into a cell like "['a', 'b']": it looks converted, but no spreadsheet or parser downstream can use it, and the failure only shows up later, in someone else's hands.
The jq one-liner
On the command line, jq handles the whole job — headers included:
jq -r '(.[0] | keys_unsorted) as $k | $k, map([.[ $k[] ]])[] | @csv' data.json > out.csvThe @csv filter is doing the unglamorous work that makes this safe: it quotes values containing commas, quotes, or newlines exactly the way the CSV standard requires. That is the difference between a converter and a string join — and it is why hand-rolled conversions that split on commas in a text editor produce files that fall apart the first time a value contains one.
Common mistakes and how to fix them
- Trusting the first record for the columns. Cause: fieldnames taken from data[0] alone. Fix: build the union of keys across every record first (snippet above) — silent column loss is the worst failure mode because nothing looks wrong.
- Stringifying nested objects into cells. Cause: converting without flattening, so a cell ends up holding "{'name': 'Alice'}". Fix: flatten with json_normalize or jq's paths first; a cell should hold a value, not a data structure.
- Opening the CSV in Excel and seeing one giant column. Cause: your locale's Excel expects semicolons. Fix: it is the delimiter setting, not your data — import via Data → From Text/CSV, or export with the separator your audience's Excel expects.
- Losing leading zeros. Cause: Excel and Sheets reinterpret values like 00742 as numbers and trim them. Fix: for ID-like columns, this is a spreadsheet display behaviour, not a conversion error — the CSV itself is correct; format the column as text on import if the zeros matter.
- Huge files converted in a browser tab. Cause: pasting a 200 MB JSON into an online tool. Fix: anything over a few megabytes belongs in the Python or jq route, which stream through the file instead of holding it in a web page.
The traps
- Nested objects don't fit: CSV has no nesting. Flatten with json_normalize first, or the converter joins the object into a single unreadable cell.
- Non-uniform keys: if some records have fields others lack, collect every key across all records before writing — otherwise columns silently disappear.
- Commas inside values: a value like "Boston, MA" must be quoted. DictWriter, pandas, and @csv all do this automatically; a hand-rolled string join does not.
- Forgetting newline="" in Python: on Windows, the csv module without it writes a blank line after every row.
- Excel showing one column: in some locales Excel expects semicolons, not commas. If everything lands in a single column, the delimiter is the problem — not your data.
Frequently asked questions
Can CSV convert back to JSON losslessly? Only if the CSV never flattened anything. A flat table round-trips fine — every cell becomes a string, so numbers and booleans come back as text unless the tool infers types. But flattened dot-notation columns and joined arrays do not un-flatten themselves; the structure you decided away during conversion stays decided. Keep the original JSON as the master, exactly like keeping original images when you convert formats.
What if my JSON is one big object, not an array? Then there is no table yet — a single object is one row at most. Usually the array you want lives inside it, under a key like results, data, or items; extract that array and convert it. If the object is genuinely a key-value map, converting it as two columns (key, value) is the honest shape.
Why do my numbers come out as text when I convert back? Because CSV has no types — every cell is characters, and 42, true, and 2026-01-01 are all just strings that a reader may interpret. If a downstream tool needs real types, agree the interpretation explicitly (or keep a JSON Schema for the data) instead of hoping each tool guesses the same way.
Can I convert YAML the same way? Yes — YAML is a superset of JSON, so the path is YAML to JSON first, then everything on this page applies unchanged. Convert YAML to JSON covers that first step.
Try it
Paste your JSON into the JSON / YAML / CSV — it converts in your browser with nothing uploaded, and shows you exactly how nested fields get flattened.