Data that can travel.
Turn Python data into JSON and bring it back safely.
01 The idea
JSON is a text format for exchanging structured data. Python’s json module converts supported Python values to JSON text and decodes JSON text back into Python values. It is useful for configuration files and APIs, but JSON text and Python dictionaries are different things.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
import json
mission = {"name": "Orbit", "ready": True, "crew": 2}
payload = json.dumps(mission)
restored = json.loads(payload)
print(payload)
print(restored["ready"]){"name": "Orbit", "ready": true, "crew": 2}
True03 Under the hood
- 1
dumps() creates a string. loads() accepts a string and parses it. The final s helps you remember the string-oriented APIs.
- 2
JSON uses true, false, and null; Python uses True, False, and None. The module handles those conversions.
- 3
Only supported data shapes serialize directly. A custom class or a set needs an explicit conversion. For files, dump() and load() work with open file objects. Catch JSONDecodeError when parsing untrusted or malformed text.
04 Your turn, builder
Decode the JSON text {"tasks": ["build", "test"]} and print the number of tasks.
Reveal one possible solution +
import json
data = json.loads('{"tasks": ["build", "test"]}')
print(len(data["tasks"]))05 Check your signal
What does json.dumps(...) return?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.