json
The json module turns Python dicts and lists into JSON text and back.
Used in 49 lessons of the course, from 00.02.
JSON is the text format almost every API uses, including LLM responses and tool calls. The json module translates between that text and Python objects.
json.dumps(obj)turns an object into a JSON string. The trailing "s" means string.json.loads(text)reads a JSON string and gives you back dicts, lists, strings, numbers,True/False, orNone.json.dumpandjson.load, without the "s", do the same with files.
In the course you'll see import json used to print results readably with indent=2 and to read the JSON a model returns. Notice the differences: JSON uses true, false, and null, and its strings always use double quotes. That's why calling str() on a dict isn't enough: the result wouldn't be valid JSON.
Reach for it when: you need to send, store, or read structured data as text, or when you want to print a nested dict readably.
Examples
Common mistake
import json
text = "{'name': 'Ada'}"
print(json.loads(text))Why: That text looks like a Python dict, but JSON requires double quotes. It usually happens when someone used `str(dict)` instead of `json.dumps`.
How to write it: Produce the text with json.dumps, and use double quotes: '{"name": "Ada"}'.
Common mistake
import json
text = json.dumps({"city": "Lima"})
print(text["city"])Why: `dumps` returns a string, not a dict. You can't index a string with a key.
How to write it: Use json.loads(text) to get a dict before asking for ["city"].
