Python Read/Write JSON
JSON is the format APIs, config files and test data use most. Python’s built-in json module converts JSON text into dictionaries and lists, and back again, in one call.
- Parse JSON strings with json.loads
- Create JSON with json.dumps
- Read and write JSON files
- Handle nested data and errors
JSON and Python types
| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
string "..." | str |
| number | int or float |
true / false | True / False |
null | None |
Parse a JSON string: loads
import json text = '{"id": 7, "name": "Asha", "active": true, "skills": ["python", "sql"], "manager": null}'user = json.loads(text) print(type(user).__name__)print(user["name"], user["skills"][0], user["active"], user["manager"])dict Asha python True None
Create a JSON string: dumps
import json report = {"suite": "login", "passed": 12, "failed": 0, "ok": True, "notes": None}print(json.dumps(report))print(json.dumps(report, indent=2, sort_keys=True)){"suite": "login", "passed": 12, "failed": 0, "ok": true, "notes": null}
{
"failed": 0,
"notes": null,
"ok": true,
"passed": 12,
"suite": "login"
}ensure_ascii=False keeps non-English characters readable instead of \u escapes: json.dumps({"city": "Pune"}, ensure_ascii=False).
Write a JSON file: dump
dump (without the s) writes straight to a file:
import json config = { "base_url": "https://sqatools.in", "browsers": ["chromium", "firefox"], "timeouts": {"page": 30, "api": 10},}with open("config.json", "w", encoding="utf-8") as f: json.dump(config, f, indent=2) print(open("config.json", encoding="utf-8").read()){
"base_url": "https://sqatools.in",
"browsers": [
"chromium",
"firefox"
],
"timeouts": {
"page": 30,
"api": 10
}
}Read a JSON file: load
import json with open("config.json", encoding="utf-8") as f: config = json.load(f) print(config["timeouts"]["api"])for browser in config["browsers"]: print("run on", browser)10 run on chromium run on firefox
Remember the pairs: loads / dumps work with strings, load / dump work with files.
Work with nested API data
import json response = json.loads("""{"page": 1, "data": [ {"id": 1, "email": "asha@example.com", "orders": [120, 80]}, {"id": 2, "email": "ravi@example.com", "orders": []}, {"id": 3, "email": "meena@example.com", "orders": [300]}]}""") for user in response["data"]: total = sum(user["orders"]) print(f'{user["id"]} {user["email"]:<20} {total}') print([u["email"] for u in response["data"] if u["orders"]])print(response.get("next_page", "no more pages"))1 asha@example.com 200 2 ravi@example.com 0 3 meena@example.com 300 ['asha@example.com', 'meena@example.com'] no more pages
Update a JSON file
Read, change, write back:
import json with open("config.json", encoding="utf-8") as f: config = json.load(f) config["browsers"].append("webkit")config["timeouts"]["page"] = 45 with open("config.json", "w", encoding="utf-8") as f: json.dump(config, f, indent=2) print(json.load(open("config.json", encoding="utf-8"))["browsers"])['chromium', 'firefox', 'webkit']
Invalid JSON
JSON is stricter than Python: keys need double quotes and trailing commas are not allowed.
import json for text in ['{"ok": true}', "{'ok': true}", '{"a": 1,}']: try: print(json.loads(text)) except json.JSONDecodeError as e: print("invalid:", e.msg, "at position", e.pos){'ok': True}
invalid: Expecting property name enclosed in double quotes at position 1
invalid: Illegal trailing comma before end of object at position 7Custom objects
json.dumps only knows the basic types. Convert other objects first, for example with default=:
import jsonfrom datetime import date order = {"id": 99, "placed": date(2026, 11, 2), "tags": {"gift"}} def to_json(value): if isinstance(value, date): return value.isoformat() if isinstance(value, set): return sorted(value) raise TypeError(f"cannot serialise {type(value).__name__}") print(json.dumps(order, default=to_json)){"id": 99, "placed": "2026-11-02", "tags": ["gift"]}Check your understanding
Predict the output
import jsondata = json.loads('[1, "two", null, true, {"k": 3.5}]')print(data, json.dumps(data))[1, 'two', None, True, {'k': 3.5}] [1, "two", null, true, {"k": 3.5}]null becomes None and true becomes True in Python; dumps converts them back to JSON spellings.
Quick quiz
1. Which function parses a JSON string into Python objects?
loads = load from a string; load reads a file object.
2. What does JSON null become in Python?
JSON null maps to Python None.
3. Which makes the output easy to read with line breaks?
indent pretty-prints nested data.
Exercise: summarise test results
Parse the JSON results, print the pass percentage and the names of failed tests.
'[{"name": "login", "status": "pass"}, {"name": "search", "status": "fail"}, {"name": "cart", "status": "pass"}, {"name": "pay", "status": "fail"}]'Pass rate: 50% Failed: search, pay
Hint 1
Count with a comprehension: [r for r in results if r["status"] == "pass"].
import json raw = '[{"name": "login", "status": "pass"}, {"name": "search", "status": "fail"}, {"name": "cart", "status": "pass"}, {"name": "pay", "status": "fail"}]'results = json.loads(raw) passed = [r for r in results if r["status"] == "pass"]failed = [r["name"] for r in results if r["status"] == "fail"]print(f"Pass rate: {len(passed) / len(results):.0%}")print("Failed:", ", ".join(failed))Pass rate: 50% Failed: search, pay
json.loads turns the text into a list of dicts, and the comprehensions filter by status. The :.0% format prints the ratio as a whole percentage.
Program Practice
38 Python File Handling Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python JSON FAQ
How do I read a JSON file in Python?
with open("data.json", encoding="utf-8") as f: data = json.load(f).
What is the difference between json.load and json.loads?
json.load reads from a file object; json.loads parses a string.
How do I pretty print JSON in Python?
print(json.dumps(data, indent=2)). Add sort_keys=True to sort the keys.
Why does json.dumps fail with “Object of type datetime is not JSON serializable”?
JSON has no date type. Convert dates to strings (isoformat()) or pass a default= function to dumps.