Python Tutorial › File Handling › Read/Write JSON

Python Read/Write JSON

BeginnerLesson 42 of 4710 min read8 runnable examples

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.

Advertisement
In this lesson
  • 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

JSONPython
object {}dict
array []list
string "..."str
numberint or float
true / falseTrue / False
nullNone

Parse a JSON string: loads

Python
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"])
Output
dict
Asha python True None

Create a JSON string: dumps

Python
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))
Output
{"suite": "login", "passed": 12, "failed": 0, "ok": true, "notes": null}
{
  "failed": 0,
  "notes": null,
  "ok": true,
  "passed": 12,
  "suite": "login"
}
Note

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:

Python
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())
Output
{
  "base_url": "https://sqatools.in",
  "browsers": [
    "chromium",
    "firefox"
  ],
  "timeouts": {
    "page": 30,
    "api": 10
  }
}

Read a JSON file: load

Python
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)
Output
10
run on chromium
run on firefox
Tip

Remember the pairs: loads / dumps work with strings, load / dump work with files.

Work with nested API data

Python
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"))
Output
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:

Python
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"])
Output
['chromium', 'firefox', 'webkit']

Invalid JSON

JSON is stricter than Python: keys need double quotes and trailing commas are not allowed.

Python
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)
Output
{'ok': True}
invalid: Expecting property name enclosed in double quotes at position 1
invalid: Illegal trailing comma before end of object at position 7

Custom objects

json.dumps only knows the basic types. Convert other objects first, for example with default=:

Python
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))
Output
{"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))

Quick quiz

1. Which function parses a JSON string into Python objects?

2. What does JSON null become in Python?

3. Which makes the output easy to read with line breaks?

Exercise: summarise test results

Parse the JSON results, print the pass percentage and the names of failed tests.

Input
'[{"name": "login", "status": "pass"}, {"name": "search", "status": "fail"}, {"name": "cart", "status": "pass"}, {"name": "pay", "status": "fail"}]'
Expected output
Pass rate: 50%
Failed: search, pay
Hint 1

Count with a comprehension: [r for r in results if r["status"] == "pass"].

Program Practice

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.

Leave a Comment