Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Flatten Nested JSON Paths

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Flatten Nested JSON Paths. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

At Meta, event payloads from products like Facebook and Instagram may contain deeply nested JSON structures. Write a Python function that flattens a nested JSON-like object into a single dictionary of path-value pairs.

Task

Given a Python object data representing parsed JSON, return a flat dictionary where each key is the full path to a primitive value.

Use these rules:

  1. Nested dictionary keys are joined with .
  2. List indices are written as [i]
  3. Primitive values (str, int, float, bool, None) become final entries
  4. Empty dictionaries and empty lists should also be preserved as values at their path

Constraints

  • The input contains only dictionaries, lists, strings, integers, floats, booleans, and null-like values (None in Python)
  • Total number of dictionary entries and list elements is in the range 0 to 10^5
  • Maximum nesting depth is in the range 0 to 10^3
  • Dictionary keys are non-empty strings without . or bracket characters

Function Signature

def flatten_json(data):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output