Data & APIs

How to Flatten Nested JSON Without Losing Structure

Flatten nested JSON for exports and debugging while preserving arrays, empty containers, and keys that contain dots.

Photorealistic editorial photo for Json Flattening Guide
Data & APIs · Practical ideas for your next build

Flattening replaces a nested tree with a collection of paths and values. It helps when you need to inspect deeply nested API responses, compare configuration fields, or prepare records for a tabular export. The important decision is the path format: a convenient dotted path is not always reversible.

Choose an unambiguous path format

Consider an object with a literal key user.name alongside a nested user object containing name. Both can become user.name in a naive flattener. JSON Pointer avoids that collision by using slash-delimited segments. It escapes a literal slash as ~1 and a literal tilde as ~0. Store the exact path convention with any exported dataset so another system can interpret it.

Keep container information

A path ending in /0 could describe an array index or an object key named 0. Empty arrays and objects have no leaf values, so a leaf-only export loses them entirely. Our flattener writes an empty container marker at each container path, including the empty-string root path. This format is deliberately richer than a spreadsheet-oriented flat object.

Validate a round trip before migration

Flatten a representative record, restore it, and compare the resulting JSON structure. Include null, false, empty strings, numeric-looking keys, arrays, and empty containers in the sample. Do not compare serialized strings alone because object property order can differ without changing the data. Large numeric identifiers also need care: JavaScript JSON parsing uses numbers that may not preserve integers beyond its safe range.

Worked example

EXAMPLE
{"user":{"name":"Ada"},"tags":[]}
→ {"/user/name":"Ada","/user":{},"/tags":[],"":{}}

Can flattened JSON always be restored?

Only when paths are unambiguous and container types are retained. Leaf-only dotted formats often discard information.

Reference and further reading

Read the official documentation ↗