Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Safe Nested JSON Value Extraction

Medium
Codingerror handlingjson parsingpython
Asked 2mo ago|
Micro1
Micro1
Asked 1 times

Problem

Given a parsed JSON-like Python object data (built from nested dictionaries, lists, strings, numbers, booleans, and None) and a path array, write a function that safely returns the value at that path without raising an exception. Each path element is either a string key for dictionaries or an integer index for lists. If any step is invalid, return default instead.

Constraints

  • 0 <= len(path) <= 10^4
  • data may contain nested dictionaries, lists, primitive values, and None
  • Path elements are only strings or integers
  • The function must not raise KeyError, IndexError, or TypeError for invalid paths

Function Signature

def safe_get(data, path, default=None):

You are practicing as a guest. Sign up free to run your code against the sample data. Your draft stays right here.

Sign up freeI have an account
def solve(rows):
    counts = {}
    for row in rows:
        ...
    return result
Sign up to unlock solutions
Next questions
McKinsey &Flatten Deeply Nested JSONMediumMetaFlatten Nested JSON PathsEasyYelpFlatten Nested Dictionary KeysEasy
Python 3.10