JSON is how most APIs, configuration files and web apps exchange data. Working with JSON in Python takes one built-in module, json, and four functions. This lesson shows each of them, how JSON types become Python types, and a worked example that reads a list of orders and writes a summary.
Playing loads the video from YouTube. Watch on YouTube
From Python to JSON: dumps()
json.dumps() turns a Python object into a JSON string. indent makes it readable; leave it out for the most compact form.
import json
data = {"firstName": "Jane", "lastName": "Doe", "hobbies": ["running", "singing"],
"age": 35, "member": True, "manager": None}
json_string = json.dumps(data, indent=2)
print(json_string){
"firstName": "Jane",
"lastName": "Doe",
"hobbies": [
"running",
"singing"
],
"age": 35,
"member": true,
"manager": null
}Notice the changes: True became true and None became null. JSON has its own spelling for these.
From JSON to Python: loads()
json.loads() goes the other way, from a JSON string to Python objects you can index and loop over.
loaded = json.loads(json_string)
print(loaded["hobbies"][0], type(loaded["age"]), loaded["manager"])running <class 'int'> NoneHow JSON types map to Python
- JSON object becomes a dict, and a JSON array becomes a list.
- Strings stay strings; numbers become int or float.
- true and false become True and False; null becomes None.
- JSON keys are always strings: a dict with number keys comes back with string keys.
Reading and writing files: dump() and load()
The versions without the s work with files instead of strings. Open the file with an explicit encoding so non-English text survives on every system.
with open("person.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("person.json", encoding="utf-8") as f:
person = json.load(f)
print(person["firstName"])JaneWorked example: a list of orders in, a summary out
Here is a typical task. An API returns orders as JSON; you need each customer’s number of orders and total spend, saved as JSON for the next step. The empty order is included on purpose: summing an empty list gives 0, so it needs no special case.
orders_json = """
[
{"id": 101, "customer": "Lena", "items": [{"sku": "CASE", "qty": 2, "price": 19.99}]},
{"id": 102, "customer": "Omar", "items": [{"sku": "CABLE", "qty": 3, "price": 7.5},
{"sku": "CASE", "qty": 1, "price": 19.99}]},
{"id": 103, "customer": "Lena", "items": []}
]
"""
orders = json.loads(orders_json)
summary = {}
for order in orders:
total = sum(item["qty"] * item["price"] for item in order["items"])
customer = summary.setdefault(order["customer"], {"orders": 0, "total": 0.0})
customer["orders"] += 1
customer["total"] = round(customer["total"] + total, 2)
print(json.dumps(summary, indent=2))
with open("summary.json", "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2){
"Lena": {
"orders": 2,
"total": 39.98
},
"Omar": {
"orders": 1,
"total": 42.49
}
}Reading an API response
Most JSON you meet comes from an API. Whatever library fetched it, you end up with text, and json.loads() turns it into dictionaries and lists you can filter like any other Python data. Missing values arrive as None:
response_text = '{"results": [{"name": "Cable", "stock": 12}, {"name": "Case", "stock": 0}], "next": null}'
payload = json.loads(response_text)
out_of_stock = [r["name"] for r in payload["results"] if r["stock"] == 0]
print(out_of_stock, payload["next"] is None)['Case'] TrueTwo dumps() options help when people read the output: indent for line breaks, and sort_keys=True so the keys always come out in the same order, which makes two files easy to compare.
print(json.dumps({"b": 2, "a": 1}, sort_keys=True)){"a": 1, "b": 2}Three errors you will meet, and the fix
The first is malformed JSON. A trailing comma is the usual culprit, because Python allows one and JSON doesn’t. json.JSONDecodeError tells you exactly where the problem is:
try:
json.loads('{"name": "Jane", "age": 35,}')
except json.JSONDecodeError as e:
print("Bad JSON:", e.msg, "at line", e.lineno, "column", e.colno)Bad JSON: Expecting property name enclosed in double quotes at line 1 column 28The second: dates, sets and your own classes have no JSON form, so dumps() raises a TypeError. Pass default=str to turn anything unknown into text:
from datetime import date
try:
json.dumps({"day": date(2026, 11, 17)})
except TypeError as e:
print("TypeError:", e)
print(json.dumps({"day": date(2026, 11, 17)}, default=str))TypeError: Object of type date is not JSON serializable
{"day": "2026-11-17"}The third surprise is accented text written as escape codes. That’s valid JSON, but hard to read; ensure_ascii=False keeps the characters as they are:
print(json.dumps({"city": "Zürich"}), json.dumps({"city": "Zürich"}, ensure_ascii=False)){"city": "Zürich"} {"city": "Zürich"}JSON or CSV?
Use CSV when the data is a flat table, one row per record with the same columns, and people will open it in a spreadsheet. Use JSON when records are nested, like an order with a list of items, when fields vary from record to record, or when another program will read the file. Many projects use both: JSON to receive data from an API and CSV to hand a summary to someone who works in Excel.
When a file might be missing or malformed, wrap the load in the try and except pattern from the previous lesson and catch FileNotFoundError and json.JSONDecodeError. Next in the series: reading and writing CSV files.
Want to go further?
I teach professionals one to one, and I build these systems for businesses. See Python AI mentoring or see what I build.