Python · Chapter 33 of 45

Python JSON

JSON is a text format for structured data — the standard for web APIs. Python's built-in `json` module converts between JSON strings and Python objects.

`json.loads()` parses a string. `json.dumps()` serialises to a string.

Files

`json.load(file)` and `json.dump(obj, file)` work directly with file objects.

Mapping

dict ↔ object, list ↔ array, str ↔ string, int/float ↔ number, True/False ↔ true/false, None ↔ null.

Example 1 (python)
import json
data = {"name": "Ana", "roles": ["admin", "user"]}
text = json.dumps(data, indent=2)
print(text)
Output
{
  "name": "Ana",
  "roles": [
    "admin",
    "user"
  ]
}

Serialise a dict to pretty JSON.

Example 2 (python)
import json
json_str = '{"x": 1, "y": [2, 3]}'
obj = json.loads(json_str)
print(obj["y"])
Output
[2, 3]

Parse JSON string to a Python dict.

Key points

  • `json.dumps(obj)` → string.
  • `json.loads(str)` → object.
  • `json.dump/load` for files.
  • JSON keys are always strings.
💡 Note: Datetime and set are NOT JSON-serialisable by default — convert to string or list first.

📝 Quick Quiz

1. Which converts a Python dict to a JSON string?

2. JSON keys are always:

3. `json.loads(text)` returns: