JSON serialization with the json module

RoadmapsPython

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

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

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

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()

Next: CSV files with the csv module

Return to Python Roadmap