Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Into the real world
EXPERIMENT 21 / 101

Data that can travel.

Turn Python data into JSON and bring it back safely.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

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.

json.py
import json

mission = {"name": "Orbit", "ready": True, "crew": 2}
payload = json.dumps(mission)
restored = json.loads(payload)

print(payload)
print(restored["ready"])
↳ EXPECTED OUTPUT
{"name": "Orbit", "ready": true, "crew": 2}
True

03 Under the hood

  1. 1

    dumps() creates a string. loads() accepts a string and parses it. The final s helps you remember the string-oriented APIs.

  2. 2

    JSON uses true, false, and null; Python uses True, False, and None. The module handles those conversions.

  3. 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

A SMALL MISSION

Decode the JSON text {"tasks": ["build", "test"]} and print the number of tasks.

Reveal one possible solution +
one_possible_solution.py
import json

data = json.loads('{"tasks": ["build", "test"]}')
print(len(data["tasks"]))

05 Check your signal

QUICK SIGNAL CHECK

What does json.dumps(...) return?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.