medium +20 pts

Flatten nested JSON

Transform nested JSON objects into a flat dictionary using dot notation for keys.

Write a function `flatten_json(data)` that takes a JSON-serializable object (dict, list, str, int, float, bool, None) and returns a flat dictionary where nested keys are joined with dots. For lists, use the index as the key segment (e.g., `"items.0"`). Empty objects and empty lists should be preserved as empty dict/list values. If the top-level value is not a dict or list, the key is an empty string `""`. If the top-level value is an empty dict, return an empty dictionary. If the top-level value is an empty list, return `{"": []}`. The result should be a plain `dict` with string keys.

Constraints

- Input is a valid JSON value (dict, list, primitive). - Depth is at most 100. - Keys are non-empty strings. - List indices are integers starting at 0. - Output must not contain any nested dict or list values, except as the value for empty objects/lists. - Complexity: O(N) where N is total number of keys/elements.

Example

>>> flatten_json({"a": 1, "b": {"c": 2}})
{"a": 1, "b.c": 2}

>>> flatten_json({"a": [1, {"b": 2}]})
{"a.0": 1, "a.1.b": 2}

>>> flatten_json({})
{}

>>> flatten_json([])
{"": []}
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a helper recursive function that tracks the current key prefix.
When encountering a list, iterate with index and append the index as a key segment.
Empty dict/list should not be recursed into; store them as values directly.
The top-level key prefix starts as an empty string; handle the case where the root is an empty dict separately.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.