Flatten nested JSON/dicts into dot-notation keys and unflatten back
pip install philiprehberger-flatten-jsonFlatten nested JSON/dicts into dot-notation keys and unflatten back.
pip install philiprehberger-flatten-json
from philiprehberger_flatten_json import flatten, unflatten
nested = {"a": {"b": {"c": 1}}, "d": [2, 3]}
flatten(nested)
# {"a.b.c": 1, "d.0": 2, "d.1": 3}
unflatten({"a.b.c": 1, "d.0": 2, "d.1": 3})
# {"a": {"b": {"c": 1}}, "d": [2, 3]}
# Custom separator
flatten(nested, separator="/")
# {"a/b/c": 1, "d/0": 2, "d/1": 3}
# Max depth
flatten(nested, max_depth=1)
# {"a": {"b": {"c": 1}}, "d": [2, 3]}
# Prefix
flatten(nested, prefix="root")
# {"root.a.b.c": 1, "root.d.0": 2, "root.d.1": 3}
# Keep numeric keys as dict
unflatten({"a.0": 1, "a.1": 2}, list_as_dict=True)
# {"a": {"0": 1, "1": 2}}
from philiprehberger_flatten_json import flatten, unflatten
data = {"users": [{"name": "Alice", "age": 30}], "meta": {"version": 2}}
flat = flatten(data)
# {"users.0.name": "Alice", "users.0.age": 30, "meta.version": 2}
restored = unflatten(flat)
# {"users": [{"name": "Alice", "age": 30}], "meta": {"version": 2}}
| Function | Description |
|---|---|
flatten(data, *, separator=".", max_depth=0, prefix="") | Flatten nested dict/list into dot-notation keys |
unflatten(data, *, separator=".", list_as_dict=False) | Restore nested structure from flat dict |
flatten()
data — Nested dict or listseparator — Key separator (default ".")max_depth — Max depth to flatten, 0 = unlimitedprefix — String to prepend to all keysunflatten()
data — Flat dict with composite keysseparator — Key separator used during flatteninglist_as_dict — When True, numeric keys stay as dict keys instead of converting to listspip install -e .
python -m pytest tests/ -v
If you find this project useful: