How to Flatten Nested JSON (and Unflatten It)
Turning a deeply nested object into flat dot.notation keys — what it's for, the notation, and how to do it (and reverse it) in JavaScript and Python.
Spreadsheets, dataframes, and most key-value stores want flat data — one level of keys, no nesting. But the JSON you get from an API is usually nested several layers deep. Flattening bridges the gap: it rewrites a nested object into a single-level one whose keys encode the original path. Here's exactly what that means and how to do it.
What does “flatten JSON” mean?
Flattening collapses nesting into compound keys. Objects contribute a dotted segment; arrays contribute a bracketed index. This nested document:
{
"active": true,
"user": {
"name": "Ada",
"roles": ["admin", "beta"]
}
}
flattens to a single level:
{
"active": true,
"user.name": "Ada",
"user.roles[0]": "admin",
"user.roles[1]": "beta"
}
Every value is now reachable by a single string key that describes where it came from — and the whole thing fits neatly into one row of a table.
Why flatten nested JSON?
- CSV & spreadsheets. A flat object maps directly to columns — it's the step behind any JSON-to-CSV or JSON-to-Excel export.
- Dataframes. Tools like pandas expect tabular input; flattening gives each path its own column.
- Key-value stores & search indexes. Many expect single-level documents, or index flat fields more predictably.
- Diffing & filtering. Comparing two flat maps by key is simpler than walking two trees.
Flatten JSON in JavaScript
A short recursive walk handles it — build the key as you descend, and assign when you hit a primitive:
function flatten(value, prefix = "", out = {}) {
if (Array.isArray(value)) {
value.forEach((v, i) => flatten(v, `${prefix}[${i}]`, out));
} else if (value && typeof value === "object") {
for (const [k, v] of Object.entries(value)) {
flatten(v, prefix ? `${prefix}.${k}` : k, out);
}
} else {
out[prefix] = value; // reached a leaf
}
return out;
}
flatten({ user: { name: "Ada", roles: ["admin", "beta"] } });
// { "user.name": "Ada", "user.roles[0]": "admin", "user.roles[1]": "beta" }
If you'd rather not hand-roll it, the flat package does the same (and unflattens).
Flatten JSON in Python
The same recursion, in Python — or reach for pandas.json_normalize when your goal is a dataframe:
def flatten(value, prefix="", out=None):
if out is None:
out = {}
if isinstance(value, list):
for i, v in enumerate(value):
flatten(v, f"{prefix}[{i}]", out)
elif isinstance(value, dict):
for k, v in value.items():
flatten(v, f"{prefix}.{k}" if prefix else k, out)
else:
out[prefix] = value
return out
# For tabular output:
import pandas as pd
pd.json_normalize(data) # nested objects -> dotted columns
Unflattening (the reverse)
Flattening is lossless as long as your keys don't themselves contain the delimiter characters. To go back, split each key on its . and [index] segments and rebuild the objects and arrays. The one real pitfall: a source key that literally contains a dot (e.g. "user.name" as an actual key) collides with the path produced by nesting — if your data has such keys, choose a delimiter they don't use, or escape it.
Flatten JSON without code
For a one-off — flattening an API response to paste into a sheet, or to skim every leaf value at once — a tool is quicker than writing the function. Our free JSON Flatten tool flattens (and unflattens) in the browser, fully client-side (disclosure: I built it). From there, JSON to CSV turns the flat result into a spreadsheet, and the JSON formatter helps you read the original structure first.
FAQs
What does it mean to flatten JSON?
Convert a nested structure into a single-level object whose keys encode the path — {"user":{"name":"Ada"}} becomes {"user.name":"Ada"}, with arrays as tags[0].
Why flatten nested JSON?
Flat data loads cleanly into CSV, spreadsheets, dataframes, and key-value stores, and is easier to diff and filter.
How do I flatten nested JSON in JavaScript?
Recurse the structure, appending .key for objects and [i] for arrays, assigning primitives to the built-up key (see the function above) — or use the flat package.
How are arrays handled?
As indexed keys like tags[0], tags[1]. Pick one convention and keep it consistent so it can be parsed back.
Can I unflatten back to nested JSON?
Yes — split keys on their delimiters and rebuild. It's lossless unless your original keys contain those delimiters. The JSON Flatten tool does both directions.