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:
| JSON | Python |
|---|---|
object {...} | dict |
array [...] | list |
| string, number | str, int/float |
true / false / null | True / 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.
Parsing an API reply
A JSON reply from a web service becomes plain dicts and lists, which are structures you already know how to walk.
import json response = '{"team": "blue", "members": [{"name": "mia", "score": 82}, {"name": "leo", "score": 91}]}' data = json.loads(response) print(data["team"]) for member in data["members"]: print(member["name"], member["score"]) print(json.dumps({"ok": True, "count": 2}))
Output
blue mia 82 leo 91 {"ok": true, "count": 2}
Nothing new is needed to work with the parsed data. A JSON object becomes a dict, a JSON array becomes a list, and nesting works exactly as it looks, so data["members"] is a list of dicts you loop over.
The last line goes the other direction. json.dumps turns Python values into a JSON string, and notice that Python's True is written as lowercase true, because that is what the JSON format requires.
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.
Editing a config and dumping it back
A parse, a small edit, and a dump. This is the shape of most config handling code you will write.
import json config_text = '{"host": "localhost", "port": 8000}' config = json.loads(config_text) config["retries"] = 3 print(json.dumps(config, sort_keys=True))
Output
{"host": "localhost", "port": 8000, "retries": 3}json.loads returns an ordinary dict with no special wrapper type, which is why config["retries"] = 3 needs no ceremony at all.
sort_keys=True makes json.dumps emit keys in alphabetical order. That matters more than it sounds: stable ordering means two dumps of equivalent data produce byte-identical text, which keeps generated files diff-friendly in version control.
Totaling an order list
The orders arrive as a JSON array. Parsing gives a list of dicts, and one sum over a generator expression computes the total owed.
import json orders_text = '[{"item": "tea", "qty": 2, "price": 3.5}, {"item": "scone", "qty": 1, "price": 4.0}]' orders = json.loads(orders_text) total = sum(o["qty"] * o["price"] for o in orders) print(total)
Output
11.0A JSON array at the top level becomes a Python list, so orders can be looped over directly with no key lookup first. Each element is a dict, making o["qty"] * o["price"] the line total, and sum with a generator expression from lesson 4-2 adds them without building an intermediate list.
The arithmetic checks out: 2 × 3.5 + 1 × 4.0 = 11.0.
How JSON types map to Python types
json.loads('{"active": true}') returns {'active': True}, with a real Python True inside.
loads translates every JSON type into its Python counterpart as it parses. Lowercase true is the only correct spelling in JSON, and dumps performs the reverse translation, writing Python's True back out as true.
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int or float |
true / false | True / False |
null | None |