Flatten a nested object
Turn a nested JSON object into a flat path → value map (e.g. for a CSV export or a config diff). Recursion or an explicit stack, leaves and empty containers.
A config diff tool shows differences as a list of path = value. We need a function that turns a nested JSON-like object into a flat object whose keys are paths to the leaves.
Task
flatten(data) (Python: flatten(data)) returns a new, flat object (dict):
- object keys are joined with a dot:
{ a: { b: 1 } }→{ "a.b": 1 }, - array elements are written as
[i]appended to the path:{ tags: ["x", "y"] }→{ "tags[0]": "x", "tags[1]": "y" }, - when the root is an array, paths start with
[i]:[1, 2]→{ "[0]": 1, "[1]": 2 }, - leaves (strings, numbers, booleans,
null/Noneand objects other than plain objects and arrays, e.g.Date/datetime) are copied as they are, - empty objects and arrays do not disappear – they go into the result as
{}/[]values, - an empty root (
{}or[]) gives an empty result, - the input must not be modified.
The order of keys in the result does not matter.
Example
| Input | Result |
|---|---|
{ "db": { "host": "localhost", "ports": [5432, 5433] }, "debug": false } | { "db.host": "localhost", "db.ports[0]": 5432, "db.ports[1]": 5433, "debug": false } |
{ "a": { "b": {} }, "c": [], "d": null } | { "a.b": {}, "c": [], "d": null } |
{ "matrix": [[1], [2, 3]] } | { "matrix[0][0]": 1, "matrix[1][0]": 2, "matrix[1][1]": 3 } |
Constraints
- Nesting depth up to 100, up to 100,000 leaves in total.
- Keys do not contain
.,[or].
Expected complexity
O(n · d) time, where n is the number of nodes and d the depth (the cost of building path strings); O(n · d) memory for the result.
Topics: Composite