Flatten a nested JSON object
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates the ability to traverse and manipulate nested JSON-like structures, emphasizing concepts such as recursion or iterative traversal, array indexing, and path string construction; it tests data structures and serialization knowledge within the Coding & Algorithms domain and targets practical implementation skills for a software engineer role. It is commonly asked to assess how interviewees flatten hierarchical payloads for data processing or API normalization, reason about mixed object/array edge cases, and map hierarchical paths to primitive values.
Constraints
- The root input is a dictionary.
- 0 <= total number of dictionary entries and list elements <= 100000.
- Keys are strings and do not contain `.`, `[` or `]`.
- Values are dictionaries, lists, or primitive JSON-like values (`str`, `int`, `float`, `bool`, `None`).
- Order of entries in the returned dictionary does not matter.
Examples
Input: ({"a": 1, "b": {"c": 2, "d": [3, 4]}, "e": [{"f": 5}, 6]},)
Expected Output: {"a": 1, "b.c": 2, "b.d[0]": 3, "b.d[1]": 4, "e[0].f": 5, "e[1]": 6}
Explanation: Each primitive value is mapped to its full path through nested dictionaries and lists.
Input: ({},)
Expected Output: {}
Explanation: An empty object has no primitive values, so the flattened result is empty.
Input: ({"x": None, "y": [True, {"z": -7}], "w": {"u": [False]}},)
Expected Output: {"x": None, "y[0]": True, "y[1].z": -7, "w.u[0]": False}
Explanation: The solution must correctly handle `None`, booleans, and negative numbers inside nested lists and dictionaries.
Input: ({"a": [[1, 2], [], [{"b": 3}]], "c": {}},)
Expected Output: {"a[0][0]": 1, "a[0][1]": 2, "a[2][0].b": 3}
Explanation: Nested lists can create paths with multiple index segments, and empty containers contribute no entries.
Input: ({"user": {"name": "Ana", "tags": ["dev", "ops"]}, "active": True},)
Expected Output: {"user.name": "Ana", "user.tags[0]": "dev", "user.tags[1]": "ops", "active": True}
Explanation: String values are primitives too, so they should appear in the flattened map.
Hints
- A depth-first traversal works well here: carry the current path as you move down the structure.
- When you move into a dictionary, append `.key` only if the current path is not empty; when you move into a list, append `[index]`.