Safely Read a Nested JSON Path

Medium ⏱ 12 min 48% acceptance ★★★★★ 4.9
API payloads nest deeply: payment.card.last4. Write dig(data, path) where path is a dot-separated string, walking the parsed dict and returning None the moment any level is missing or not a dict — no exceptions raised.

Examples

Example 1
Input
dig({'payment': {'card': {'last4': '4242'}}}, 'payment.card.last4')
Output
'4242'
Explanation

Each segment descends one level.

Example 2
Input
dig({'payment': {}}, 'payment.card.last4')
Output
None
Explanation

The chain breaks quietly at card.

Constraints

  • No try/except — check types as you walk.
  • Split the path on '.'.

Topics

JSONnested access

Companies

StripePlaidRazorpay

Hints

Hint 1

isinstance(current, dict) guards each step.

Hint 2

Return None on the first miss.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.