JSON guide · 2 min read
How to Flatten and Unflatten Nested JSON
Convert nested JSON to path-like keys, reconstruct the hierarchy and avoid collisions involving arrays, dots, empty containers and numeric keys.
What flattening changes
Flattening replaces nested structure with keys that encode paths. This can make nested values easier to compare, export or map into systems that accept only flat records.
Nested:
{"user":{"name":"Asha","address":{"city":"Kolkata"}}}
Flattened:
{
"user.name":"Asha",
"user.address.city":"Kolkata"
}Choose one path convention
Dot notation is readable for ordinary keys, while bracket notation can make arrays clearer. The unflattening step must understand exactly the same convention or reconstruction becomes ambiguous.
Literal separator characters create collisions
A literal key named user.name can collide with the nested path user then name if both become user.name. Robust flattening needs escaping or an unambiguous separator strategy when arbitrary keys are possible.
Arrays need explicit index rules
Arrays are commonly encoded with numeric path segments or brackets. Numeric-looking object keys can then become ambiguous unless the convention distinguishes a property named "0" from array index 0.
Possible styles:
users.0.name
users[0].nameEmpty objects and arrays can disappear
A leaf-only flattening algorithm has no scalar value to emit for an empty object or array. If empty containers matter, the flat representation needs a marker or metadata that preserves them.
Verify round trips before trusting the transform
Flatten the source, unflatten the result and compare the reconstructed structure with the original. Round-trip tests quickly expose path collisions, array ambiguity and lost empty containers.
- Test separator characters in property names.
- Test arrays and numeric-looking keys.
- Test empty objects and arrays.
- Structurally compare the reconstructed value with the source.
Common questions
Frequently asked questions
Can flattened JSON always be restored exactly?
Only when the path convention preserves enough information and handles ambiguous keys, arrays and empty containers explicitly.
Is flattened JSON still valid JSON?
Yes when represented as a normal JSON object. The path strings are simply property names.
Why did an empty object disappear after flattening?
Leaf-only flattening has no scalar value to emit for an empty container, so preserving it requires an explicit convention.