Skip to main content
CheckTown
Data Tools

JSON Flatten: Convert Nested to Flat and Back

Published 5 min read
In this article

What Is JSON Flattening?

JSON flattening converts a deeply nested JSON object into a flat key-value structure using dot-notation paths. Each leaf value in the original object gets a unique path like 'user.address.city' that describes its position in the hierarchy.

The reverse operation, unflattening, takes dot-notation paths and reconstructs the original nested structure. Together, flatten and unflatten let you transform JSON between nested and flat representations without losing any data.

How JSON Flattening Works

The flattening algorithm recursively traverses the JSON tree, building a path string as it descends into nested objects and arrays.

  • Recursive traversal — the algorithm walks every key in the object, appending each key to a growing dot-separated path
  • Array index notation — array elements use bracket notation like 'items[0].name' to preserve their position in the flattened output
  • Leaf collection — when a primitive value (string, number, boolean, null) is reached, the full path and value are stored as a flat key-value pair

Try it free — no signup required

Flatten or Unflatten JSON →

When To Use JSON Flattening

Flattened JSON is useful whenever you need to work with nested data in flat-only systems or compare complex structures.

  • Database storage — store nested config or metadata in flat key-value tables without schema changes
  • CSV export — convert nested JSON records to flat rows suitable for spreadsheet import or tabular display
  • Config comparison — flatten two config files and diff the flat keys to quickly spot which nested values changed

Frequently Asked Questions

Does flattening preserve data types?

Yes. All primitive values (strings, numbers, booleans, null) are preserved exactly. Arrays become indexed paths like 'items[0]', and nested objects become dot-separated paths. Unflattening reconstructs the original types from the paths.

What happens with very deep nesting?

The flattener handles any nesting depth. Very deep objects produce long path strings, but this has no functional limit. If performance matters, most implementations use iterative approaches to avoid call stack issues with thousands of nesting levels.

Can I flatten JSON with duplicate keys?

JSON does not allow duplicate keys at the same level by specification. If your parser accepts them, only the last value for each key survives parsing. The flattener works on the parsed object, so duplicates are already resolved before flattening begins.

Related Tools