json.loads, recursion & flattening

Nested JSON

Lesson 17 of 20 · 12 min · Module 5: Real-world data

APIs return JSON with objects inside lists inside objects. Flattening that structure into simple keys makes it easy to search, compare, or export to a spreadsheet.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Parse JSON into Python objects
  • Walk nested data recursively
  • Build keys that describe a path

The idea

json.loads(text) turns JSON text into dicts, lists, strings, numbers, booleans, and None. A recursive function, one that calls itself, walks nested structures of any depth: handle a dict or list by visiting each child, and anything else is a final value.

import json
data = json.loads('{"user": {"name": "Ana", "langs": ["py", "sql"]}}')
print(data["user"]["langs"][1])

01JSON maps to Python

Objects become dicts, arrays become lists, true/false become True/False, and null becomes None. After json.loads, it is ordinary Python data.

import json
print(json.loads('[true, null, 1.5]'))
Output
[True, None, 1.5]

02Recursion fits nested data

You cannot know in advance how deep the nesting goes. A function that handles one level and calls itself for the children handles every depth with the same few lines.

03The prefix is the path so far

Each recursive call receives the key path of its parent. Adding ".name" or ".0" builds the full address, much like a folder path.

Your turn

Write flatten(data) that returns a flat dict with dotted keys: {"user": {"name": "Ana", "langs": ["py"]}} becomes {"user.name": "Ana", "user.langs.0": "py"}. List positions become numbers in the key. Empty dicts and lists produce no keys. Non-container values at the top level give {"": value}.

What the checks look for

  • Flattens nested objects and lists
  • Works with JSON text and keeps None, numbers and booleans
  • Empty containers produce no keys
  • Handles a top-level list and a plain value
Try it in the editor →

Take this with you

Recursion walks nested data one level at a time.

Go a little further

Write unflatten(flat) that rebuilds the nested structure from the dotted keys.

Learn Python Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →