JSON serialization with the json module
Overview
The `json` module converts between Python objects and JSON text. Four functions cover almost everything — remember them by the pattern 's = string, no-s = file': import json json.dumps(obj) # object -> JSON string json.loads(text) # JSON string -> object json.dump(obj, f) # object -> write to file json.load(f) # read from file -> object The type mapping is fixed: dict↔object, list↔array, str↔string, int/float↔number, True/False↔true/false, None↔null. Useful options: `indent=2` for pretty output, `sort_keys=True` for stable ordering, and `default=str` (or a custom function) to serialize types JSON doesn't know natively, like `datetime` or `Decimal`.
JSON is the lingua franca of APIs, config files, and data interchange. Reading a request body, writing a config, caching a result, or talking to any web service almost always means serializing to and from JSON.
Where used: REST API request/response bodies, Config files and app settings, Caching and message payloads
Why learn this
- Every API and most config formats move data as JSON — this is the read/write layer for all of it.
- Knowing the type mapping and the `default=` escape hatch prevents the common 'Object of type datetime is not JSON serializable' crash.
Code walkthrough
import json
obj = {'id': 1, 'tags': ['a', 'b'], 'active': True, 'note': None}
text = json.dumps(obj)
print(text)
back = json.loads(text)
print(back['active'], type(back['active']).__name__)
Focus: json.loads(text) (JSON true/null become Python True/None)
Common mistakes
- Confusing dumps/loads with dump/load: The `s` means 'string'. `dumps`/`loads` work with strings; `dump`/`load` work with an open file object. Passing a file to `dumps` or a string to `load` fails.
- Trying to serialize non-JSON types: `datetime`, `Decimal`, `set`, and custom objects raise `TypeError: not JSON serializable`. Convert them first, or pass `default=str`/a custom encoder function to tell `json` how to represent them.
- Expecting non-string dict keys to survive: JSON object keys are always strings, so `json.dumps({1: 'a'})` emits `{"1": "a"}` and a round-trip gives you the key back as the string `'1'`, not the int `1`.
Glossary
- serialization
- Converting an in-memory object into a storable/transmittable format like a JSON string. Example: `json.dumps({'a': 1})`.
- deserialization
- Rebuilding an in-memory object from a serialized string. Example: `json.loads('{"a": 1}')`.
Recall questions
- What is the difference between `json.dumps` and `json.dump`?
- What happens when you `json.dumps` a `datetime` object, and how do you handle it?
- If you serialize `{1: 'a'}` to JSON and load it back, what is the key?
Understanding checks
What JSON string does this print?
{"ok": true, "val": null}
Python `True` maps to JSON `true` and `None` maps to `null` (both lowercase, unquoted). Strings use double quotes in JSON output.
A developer says 'json.dumps and json.dump are the same, just spelled differently.' Correct this.
They differ: `dumps` returns a string, `dump` writes to a file object.
The `s` denotes 'string'. `json.dumps(obj)` produces a string in memory; `json.dump(obj, file)` streams the JSON into an open file. Using the wrong one (e.g. `dump` without a file) raises an error.
Practice tasks
Round-trip with pretty output
Given the dict below, produce a pretty-printed JSON string with 2-space indentation and keys sorted, then parse that string back into a Python object and print the value of 'name'.
Continue learning
Previous: Reading and writing files with open()