38. Flatten Nested JSON
Difficulty: Medium · Topic: Data wrangling
Before loading events into a table, nested JSON is flattened into columns. Write flatten_json(obj, sep='.') for a dict obj:
- Nested dict keys are joined with
sep:{'user': {'id': 1}}becomes{'user.id': 1}. - List items use their index as the key:
{'tags': ['a', 'b']}becomes{'tags.0': 'a', 'tags.1': 'b'}. - An empty dict or list is kept as a value (
{'meta': {}}stays{'meta': {}}), so no column silently disappears. - Keys keep the order they are met in, and the input is not changed.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
flatten_json({'id': 7, 'user': {'name': 'Asha', 'geo': {'city': 'Pune'}}, 'tags': ['new', 'vip']})Expected: {'id': 7, 'user.name': 'Asha', 'user.geo.city': 'Pune', 'tags.0': 'new', 'tags.1': 'vip'}
Hints
Hint 1
Write a helperwalk(value, prefix) that adds leaves to an output dict.Hint 2
For a list,enumerate gives the index to use as the key.Hint 3
At the top level there is no prefix, so do not start keys with the separator.Learn the concepts
- Wrangling data without pandas · 5 min read. Parse, flatten, deduplicate, join and aggregate in plain Python, with SQL's null rules.
More Python problems
- Parse Log Lines into Records · Easy
- Reformat Date Strings · Easy
- CSV Rows to Typed Records · Easy
- Keep the Latest Record per Key · Medium
- Group and Aggregate without pandas · Medium
- Left Join Two Lists of Dicts · Medium
- Merge Overlapping Sessions · Hard
- Schema Validation with a Dead-Letter Queue · Hard