Skip to main content

Flatten a nested JSON object into one level, joining the keys with dots. For example, a user object with name Asha and an address object with city Pune becomes user.name = Asha and user.address.city = Pune.

Coding rounds · Intermediate 2

Short answer

Recurse through the dict and carry the path so far as a prefix. For each key, build the new path; if the value is a non-empty dict, recurse, otherwise store the value under the dotted path. Every key is visited once, so it is O(n) time, with memory for the output and a stack as deep as the nesting.

Deeper answer

First clarify the input. Ask what to do with lists: keep them as values or expand them with index numbers such as items.0.name. Ask whether keys can already contain a dot, how deep the nesting can go, and whether an empty dict should be kept.

Write flatten(obj, prefix="") that returns a new dict called out. For each key and value in obj.items(), build path = f"{prefix}.{key}" if prefix else key. If the value is a non-empty dict, tested with isinstance(value, dict) and value, call out.update(flatten(value, path)). Otherwise set out[path] = value. The non-empty test keeps an empty dict as a value, so the key is not lost.

The cost is O(n) in the total number of keys, and recursion depth equals the nesting depth. For very deep data, replace recursion with an explicit stack of prefix and dict pairs. Test an empty object, an already flat object, an empty nested dict, None values and a list value. Mention pd.json_normalize(data) as the library option when the goal is a table.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Write your own functions

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.