Flattening nested JSON means collapsing a deep structure into a single-level object whose keys are the full path to each value. It is the step that makes JSON fit a spreadsheet, a search index or a feature store — anywhere that wants flat key/value pairs rather than nesting. This guide explains exactly what flattening produces, how objects and arrays are handled, when you need it, and how to do it in code.
What flattening produces
Take a nested record:
{
"id": 1,
"name": "Ada",
"address": { "city": "London", "zip": "EC1" },
"roles": ["admin", "author"]
}
Flattened with dot-notation keys, it becomes a single level:
{
"id": 1,
"name": "Ada",
"address.city": "London",
"address.zip": "EC1",
"roles.0": "admin",
"roles.1": "author"
}
Every leaf value now has one key that is the path to reach it. Paste any document into the JSON flatten tool to see this instantly — it runs in your browser, so the data stays on your device.
How objects and arrays are handled
Objects are the simple case: each nested key is joined to its parent with a dot, as deep as the structure goes (a.b.c.d). Arrays are the decision point. Most flatteners use the index as a path segment — roles.0, roles.1 — which preserves order and keeps every element addressable. Others join an array of scalars into a single string ("admin, author"). Neither is wrong; choose based on what happens next. Index segments are right when each element matters individually; a joined string is right when the array is really one multi-valued cell.
When to flatten
- CSV and spreadsheets. A flat grid cannot hold nested objects, so flattening is the step that gives every leaf its own column. This is the core of converting JSON to CSV.
- Search indexing. Engines like Elasticsearch index flat fields; flattening with dotted keys maps nested documents onto searchable field names.
- Feature stores and analytics. Tabular data pipelines want one column per signal, which is exactly what dotted keys give you.
- Diffing and config. A flat list of
path = valuelines is sometimes easier to scan and compare than deep nesting.
Flattening vs querying
Flattening transforms the whole document into flat keys. If instead you only want a few specific values, do not flatten — query. A JSONPath expression or the path finder pulls out exactly the values you ask for and leaves the rest alone. Flatten when the destination wants every leaf; query when you want a handful. The two are complementary, and our JSONPath guide covers the query side.
Flattening in code
A recursive walk is all it takes. In Python, pandas.json_normalize() flattens records for analysis, and a small function does it without pandas:
def flatten(obj, prefix=""):
out = {}
if isinstance(obj, dict):
for k, v in obj.items():
out.update(flatten(v, f"{prefix}{k}."))
elif isinstance(obj, list):
for i, v in enumerate(obj):
out.update(flatten(v, f"{prefix}{i}."))
else:
out[prefix[:-1]] = obj # drop the trailing dot
return out
In JavaScript the same recursion applies, or libraries like flat handle it with options for the separator and array behaviour. Parse the JSON first (see parsing JSON in Python) so you are flattening a real object, not a string.
Reversing it: unflatten
Flattening is lossless when the separator is consistent, so you can rebuild the nested structure from the flat keys. The JSON unflatten tool does exactly that — useful when a system hands you dotted keys (from a form, a config loader or a flat database) and you need the original nested JSON back. The one caveat: if a real key contains your separator character, round-tripping can be ambiguous, so choose a separator your keys do not use.
Choosing a separator
The dot is the conventional separator, but it is not always safe. If your JSON keys can themselves contain dots — common with keys like "user.email" or version strings like "1.2.0" — then a flattened key becomes ambiguous and unflattening cannot tell which dot was structure and which was part of a name. The fix is to pick a separator that cannot appear in your keys, such as a slash, a pipe, or a double underscore. Most flatten tools let you set the separator; choose it once, deliberately, and keep it consistent across a pipeline so flatten and unflatten agree.
Flattening for analytics and feature stores
Flattening is a routine step in data engineering. Analytical tables, columnar stores and machine-learning feature sets all want one column per signal, and nested JSON — the natural shape of events and API payloads — does not fit that directly. Flattening event records into dotted columns is how a stream of nested JSON becomes a wide table a warehouse can query. The same applies to search: an index maps nested documents to flat field names, so address.city becomes a queryable field. In each case the destination is tabular or flat, and flattening is the adapter between the nested source and that flat target.
Deeply nested or very large documents
Two practical limits are worth knowing. A deeply nested document produces very long keys (a.b.c.d.e.f), which can be unwieldy and, in some systems, hit column-name length limits — consider flattening only the levels you actually need. And a huge array flattens into an enormous set of indexed keys (items.0 through items.9999), which is rarely what you want for a table; there you usually want one row per array element instead, which is the record-path approach from converting JSON to CSV rather than a pure flatten.
Order and round-trip safety
A good flattener preserves enough information to rebuild the original, which means keeping array indices rather than collapsing them and using a separator that cannot collide with real key names. If you only ever flatten in one direction — say, to load into a spreadsheet — these concerns matter less. But in a pipeline that flattens, edits and then unflattens, treat the separator and the array handling as a contract both ends agree on, so a value never silently changes shape on the way back.
Key takeaways
- Flattening joins every nested path into a single-level dot-notation key.
- Objects nest with dots; arrays usually become numeric segments like
roles.0. - Flatten for CSV, spreadsheets, search indexing and analytics.
- Query with JSONPath when you want a few values, not the whole document.
- Unflatten rebuilds the nested structure from flat keys.