Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Traverse and Transform Nested JSON

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

Your question is Traverse and Transform Nested JSON. 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

lululemon product attributes and order metadata can contain deeply nested JSON objects and arrays. Implement an algorithm that transforms this JSON into a flat dictionary containing one entry for every non-null primitive value.

Formal Specification

Implement flatten_metadata(data), where data is a JSON-compatible object containing dictionaries, lists, strings, numbers, booleans, and null. Return a dictionary mapping each leaf's path to its primitive value.

Use these path rules:

  1. Dictionary keys are separated by ..
  2. Array elements use zero-based bracket notation, such as items[0].sku.
  3. In dictionary keys, escape \\ as \\\\ and . as \\. before joining paths.
  4. Omit null values and empty dictionaries or lists.
  5. The input root is always a dictionary. Dictionary key order does not affect correctness.
  6. The algorithm must use an explicit stack rather than Python recursion so that deeply nested metadata does not overflow the call stack.

Constraints

  • 1 <= total JSON nodes <= 2 * 10^5
  • Maximum nesting depth is 10^4
  • Dictionary keys are non-empty strings
  • Leaf values are strings, numbers, booleans, or null
  • The input contains no cyclic references

Function Signature

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