Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Transform Nested JSON in Python

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

Your question is Transform Nested JSON in Python. 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

GEICO Claims Center services exchange large, deeply nested JSON payloads. Write a function that normalizes one payload into an ordered list of leaf records without using recursive traversal.

A leaf is any JSON scalar value, including null, a string, a number, or a Boolean. An empty object or empty array is also treated as a leaf. Preserve document order: object keys must appear in their original insertion order, and array elements must appear by ascending index.

Formal Specification

Implement flatten_json(payload). The input is a valid JSON value represented by Python dictionaries, lists, strings, integers, floats, Booleans, and None. Return a list of dictionaries. Each result dictionary must contain:

  • path: a list of object keys and zero-based array indexes from the root to the leaf
  • value: the leaf value itself

Use an iterative depth-first traversal. Do not mutate payload, and do not use recursion.

Constraints

  • The payload contains at most 2 * 10^5 objects, arrays, and scalar values.
  • Nesting depth can exceed Python's recursion limit.
  • Object keys are strings, and array indexes are nonnegative integers.
  • The output must preserve traversal order.

Function Signature

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