Flatten and Rebuild Nested JSON
Convert nested JSON objects to dotted key paths and reconstruct them, rejecting conflicting paths instead of silently overwriting.
Code
from typing import Any
def flatten(data: dict[str, Any], prefix: str = "") -> dict[str, Any]:
flat: dict[str, Any] = {}
for key, value in data.items():
path = f"{prefix}.{key}" if prefix else key
if isinstance(value, dict) and value:
flat.update(flatten(value, path))
else:
flat[path] = value
return flat
def unflatten(flat: dict[str, Any]) -> dict[str, Any]:
root: dict[str, Any] = {}
for path, value in flat.items():
parts = path.split(".")
cursor = root
for part in parts[:-1]:
existing = cursor.get(part)
if existing is None:
existing = {}
cursor[part] = existing
if not isinstance(existing, dict):
raise ValueError(f"path conflict at {part!r} in {path!r}")
cursor = existing
leaf = parts[-1]
if leaf in cursor:
raise ValueError(f"duplicate or conflicting path: {path!r}")
cursor[leaf] = value
return root
if __name__ == "__main__":
source = {
"server": {"host": "localhost", "ports": [8080, 8081], "tls": {"enabled": True}},
"name": "api",
"empty": {},
}
flat = flatten(source)
print(flat)
print(unflatten(flat) == source)
try:
unflatten({"a": 1, "a.b": 2})
except ValueError as error:
print("rejected:", error)
Output
Captured from a sandboxed run of this snippet in the build pipeline.
{'server.host': 'localhost', 'server.ports': [8080, 8081], 'server.tls.enabled': True, 'name': 'api', 'empty': {}}
True
rejected: path conflict at 'a' in 'a.b'Inside the snippet
Everything happens inside the functions flatten and unflatten.
Repetition is confined to for key, value in data.items() — the rest of the file is straight-line. ValueError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
not isinstance(existing, dict)short-circuits the flow with an earlyraisewhen its condition holds.
Using it
The main signature reads def flatten(data: dict[str, Any], prefix: str = "") -> dict[str, Any]
The demo output is labeled (rejected:), so every printed line maps back to its originating operation.
Key statements
raise ValueError(f"duplicate or conflicting path: {path!r}")
cursor[leaf] = value
return root
if __name__ == "__main__":
source = {
"server": {"host": "localhost", "ports": [8080, 8081], "tls": {"enabled": True}},
"name": "api",
"empty": {},
}
except ValueError as error:
print("rejected:", error)
if existing is None:
existing = {}
cursor[part] = existing
Interactive Tools for This Topic
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
FAQ
- Is there a failure path for bad input?
- Validation comes first — `ValueError` marks the failure at `not isinstance(existing, dict)`, before any partial work happens.
- What does Flatten and Rebuild Nested JSON print when run?
- Invoke the file as-is — the `rejected:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.