Course outline · 0% complete

0/27 lessons0%

Course overview →

JSON in and out

lesson 8-2 · ~12 min · 22/27

The data language of the internet

Programs constantly hand structured data to other programs: a weather service answers your app, a config file feeds your server, two services trade records. That exchange needs a text format both sides can parse, and the de facto standard is JSON (JavaScript Object Notation). It is the format spoken by most APIs, the web endpoints that programs call to request data from other programs, and by countless config files. JSON maps almost one-to-one onto Python:

JSONPython
object {...}dict
array [...]list
string, numberstr, int/float
true / false / nullTrue / False / None

The json module converts both directions:

import json

text = json.dumps({"name": "ada", "admin": True})   # dict -> str
data = json.loads('{"name": "ada"}')                 # str -> dict

Memory hook: dumps and loads mean dump/load string. The s-less json.dump(data, f) and json.load(f) work with an open file instead.

Code exercise · python

Run this program. A JSON reply from a web API becomes plain dicts and lists you already know how to walk.

Round-tripping to disk

Combine this with lesson 8-1 and you have persistence, saving program state between runs:

from pathlib import Path
import json

state = {"level": 3, "hp": 40}
Path("save.json").write_text(json.dumps(state, indent=2))

loaded = json.loads(Path("save.json").read_text())

indent=2 pretty-prints for humans. Two habits worth stealing:

  • Parse JSON into dicts at the boundary of your program, then convert important pieces to classes (lesson 3-2) if they carry behavior.
  • Malformed JSON raises json.JSONDecodeError. The next lesson shows how to catch it cleanly.

Code exercise · python

Your turn. Parse the config string, add a new key "retries" set to 3, and print the result with json.dumps using sort_keys=True so the key order is stable.

Code exercise · python

Your turn. The shop's orders arrive as a JSON array. Parse it, then compute the total owed: the sum of qty * price across the orders. sum with a generator expression (lesson 4-2) keeps it to one line.

Quiz

What does json.loads('{"active": true}') return?