Flatten nested JSON
Task
Before loading API responses into a table, nested objects are flattened into columns. Write flatten_json(obj) that turns nested dicts into one dict with dotted keys, so {"a": {"b": 1}} becomes {"a.b": 1}. Leave lists and other values as they are. An empty nested dict produces no keys.
Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.
Tests
| Call | Expected |
|---|---|
flatten_json({'a': 1, 'b': {'c': 2, 'd': {'e': 3}}}) | {'a': 1, 'b.c': 2, 'b.d.e': 3} |
flatten_json({'tags': ['x', 'y'], 'meta': {}}) | {'tags': ['x', 'y']} |
flatten_json({}) | {} |
flatten_json({'user': {'id': 7, 'name': None}}) | {'user.id': 7, 'user.name': None} |
- Recurse into values that are dicts, passing the key path built so far.
- Build the full path: the prefix for
ein{"b": {"d": {"e": 3}}}isb.d.
Show solution
def flatten_json(obj, prefix=''):
out = {}
for key, value in obj.items():
name = f'{prefix}.{key}' if prefix else key
if isinstance(value, dict):
out.update(flatten_json(value, name))
else:
out[name] = value
return outPassing the accumulated prefix down the recursion builds the full path at any depth. Losing the parent prefix when recursing is the common bug: it works for two levels and breaks at three.
Why this works
Passing the accumulated prefix down the recursion builds the full path at any depth. Losing the parent prefix when recursing is the common bug: it works for two levels and breaks at three.
Revise in the Python for Data Engineers guide, or test yourself with the Python practice sets.