Skip to content

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:

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 1Write a helper walk(value, prefix) that adds leaves to an output dict.
Hint 2For a list, enumerate gives the index to use as the key.
Hint 3At the top level there is no prefix, so do not start keys with the separator.

Learn the concepts

More Python problems

All Python problems