Lesson 7: Fetching & Parsing JSON

⏱ ~35 min Lesson 7 of 14 💚 Free

JSON is the language of the internet. Every major API returns JSON. Knowing how to navigate, filter, and transform JSON data is one of the most practical skills in modern programming.

Key Concepts

JSON Structure

JSON maps to Python: objects → dicts, arrays → lists, strings → str, numbers → int/float, true/false → True/False, null → None. json.loads(string) parses; json.dumps(obj) serializes.

Navigating Nested JSON

data['user']['address']['city']
Many API responses are deeply nested. Use .get() to avoid KeyError:
city = data.get('user', {}).get('address', {}).get('city', 'Unknown')

Filtering Lists of Records

users = data['results'] # list of dicts
ok_users = [u for u in users if u['state'] == 'OK']
List comprehensions work perfectly on JSON arrays of objects.

Pretty Printing

import json
print(json.dumps(data, indent=2))
This formats JSON with indentation so it's readable. Essential for debugging API responses.

✅ Check Your Understanding

1. What does json.loads(string) do?

2. How do you safely get a nested key that might not exist?

3. What is json.dumps(data, indent=2) useful for?