Flatten a Nested JSON Object

Free with account Updated Nov 19, 2026 · 7 min read
On this page

    Problem statement

    Part 1: write flatten(obj), which turns a nested JSON-style object into a single-level map from path to value. Paths join keys with "."; list elements use their index as the key. Leaf values (strings, numbers, booleans, null) are copied as they are, and an empty object or list is kept as a leaf so nothing is lost.

    Part 2: write unflatten(flat), which rebuilds the original nested object. Expect follow-ups on custom separators, keys that contain the separator, and very deep nesting.

    This comes up in practical rounds because it mirrors real work: turning nested config or event payloads into column names, environment variables or log fields, and back. There is no single LeetCode original; the closest relatives are tree traversals such as LeetCode 257, Binary Tree Paths.

    Example

    Every leaf becomes one entry whose key is the full path from the root, with list positions as path parts.
    Every leaf becomes one entry whose key is the full path from the root, with list positions as path parts.
    flatten({
      "user": {"name": "Ada", "langs": ["py", "go"], "address": {"city": "Oslo"}},
      "active": true
    })
    -> {
      "user.name": "Ada",
      "user.langs.0": "py",
      "user.langs.1": "go",
      "user.address.city": "Oslo",
      "active": true
    }
    flatten({"a": {}, "b": [], "c": null}) -> {"a": {}, "b": [], "c": null}
    unflatten(flatten(x)) == x

    Constraints (assumed)

    • Up to 10⁵ leaves; nesting depth up to 100 (deeper input is a follow-up).
    • Keys are strings without the separator; values are JSON values.

    What this question tests

    • Treating nested data as a tree and walking it with DFS while carrying the path.
    • Defining the format precisely: lists, empty containers, separators.
    • Writing the inverse and checking the round trip.

    Questions to ask first

    1. How are list elements named? (Here: by index, langs.0. Some versions use langs[0].)
    2. What happens to empty objects and lists? (Here: kept as leaf values.)
    3. Can a key contain the separator? (Here: no, and the code rejects it. See the bug section.)
    4. Should unflatten turn numeric keys back into lists? (Here: yes, when the keys are exactly 0…n−1.)
    5. How deep can it get? Recursion depth matters past a few thousand levels.