JSON data

Standard Library Tour, lesson 5 of 6

🧰 Standard Library Tour, lesson 5 of 6

JSON data

Convert between Python objects and the web's favourite data format.

9 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

JSON is the most common text format for data on the web and in config files. It looks a lot like Python dicts and lists. The json module converts both ways:

  • json.dumps(obj): Python object → JSON string
  • json.loads(text): JSON string → Python object
  • json.dump / json.load: the same, with files
Example

Python ↔ JSON

Spot the differences: JSON uses double quotes, true/false and null instead of True/False/None.

Example

Reading API-style data

Web APIs send JSON text like this. indent=2 makes output readable; add sort_keys=True to sort keys.

Quiz

What does this print?

Example

What JSON can't handle

Fix it by storing date(2025, 1, 15).isoformat(), or by passing default=str to json.dumps.

Example

Save and load a file

This is how apps remember preferences between runs. Change the theme and run it again.

Exercise

Summarize an order

Write summarize(text). It receives a JSON string like order_json and must return a JSON string with two keys:

  • "count": the number of items
  • "total": the sum of price * qty, rounded to 2 decimals