JSON guide · 6 min read
How to Flatten and Unflatten Nested JSON
Convert nested JSON to dot-path keys, rebuild the original hierarchy and avoid collisions involving arrays and literal dots.
What flattening does
Flattening turns nested paths into keys, making deeply nested values easier to compare, export or store in systems that expect flat records.
{"user":{"name":"Asha"}}
→
{"user.name":"Asha"}Define array behavior
Arrays may be represented with numeric path segments or bracket notation. The chosen convention must be consistent for unflattening to reconstruct the intended structure.
Prevent path collisions
A literal key containing a dot can collide with a nested path. Empty objects, sparse arrays and numeric-looking object keys also require explicit rules.
Verify round trips
Flatten, unflatten and compare the result with the original. A successful round trip is the best check that your path convention preserves the required structure.
Common questions
Frequently asked questions
Can flattened JSON always be restored exactly?
Only when the path convention preserves enough information and avoids ambiguous keys or unsupported structures.
Is flattened JSON valid JSON?
Yes, when represented as a normal JSON object. The dot paths are simply string property names.