🎯 What you will learn
- Read and write JSON with the json module
- Understand what an API is
- Handle data you get from the internet safely
👋 Let’s get started!
When a weather app shows the forecast, it asked a weather server through an API and got data back as JSON 🌐. JSON looks like Python dictionaries and lists — so you already speak it!
🪜 Step by step
1. 📄 JSON
JSON is text that stores data. json.loads() turns it into Python; json.dumps() turns Python into JSON.
import json
text = '{"city": "Atlanta", "temp": 72}'
data = json.loads(text)
print(data["city"])
2. 🔌 APIs
An API is a menu of requests a server understands. You send a request to a URL and get JSON back. With the requests package: requests.get(url).json()
# Outside the browser:
# import requests
# r = requests.get("https://api.example.com/weather?city=Atlanta")
# data = r.json()
3. 🛡️ Be safe with data
Never paste API keys into public code, check for missing fields, and don’t trust data blindly.
temp = data.get("temp", "unknown")
print("Temperature:", temp)
🧪 Try it!
Change the code and press ▶ Run to see what happens. You can’t break anything!
Parse a pretend API response
import json
response = '''
{"planet": "Mars", "moons": ["Phobos", "Deimos"], "day_hours": 24.6}
'''
data = json.loads(response)
print(f"{data['planet']} has {len(data['moons'])} moons:")
for moon in data["moons"]:
print(" 🌑", moon)
print("A day lasts", data["day_hours"], "hours")Save settings as JSON
import json
settings = {"theme": "dark", "volume": 7}
text = json.dumps(settings)
print(text)📖 Key words
Tap a card to flip it over!
- JSON
- A text format for sharing data 📄
- API
- A way for programs to talk to each other 🔌
- Request
- A message asking a server for data 📨
- API key
- A secret password for an API 🔑
🏆 Challenge
Parse the JSON and print the name of the oldest student.
Challenge
import json
text = '[{"name": "Sam", "age": 14}, {"name": "Lin", "age": 16}, {"name": "Ola", "age": 15}]'
Knowledge Check Quiz
- What does json.loads() do?
- What is an API?
- Where should API keys go?