Python theorytheory 0/50 · 0%
Tooling · easy

17. File-like data with json

Serializing Python data to and from JSON text.

The `json` module converts between Python objects and JSON text. `dumps`/`loads` work with strings; `dump`/`load` work with file objects.

python
import json

data = {"chain": "Base", "chainId": 8453}
text = json.dumps(data)          # '{"chain": "Base", "chainId": 8453}'
parsed = json.loads(text)        # back to a dict

JSON only supports a subset of Python types (dict, list, str, int/float, bool, None); tuples become lists, and custom objects need a converter function passed via `default=`.

`json.dumps(data, indent=2)` pretty-prints for readability.

Check your understanding

  1. 1. What does `json.dumps(obj)` return?

  2. 2. What happens to a Python tuple when serialized to JSON?

  3. 3. What does `json.loads(text)` do?