📘 Lesson 26 · Advanced

Python JSON

Handle JSON in Python with dumps, loads, file read/write, and API data parsing.

What is JSON?

JSON (JavaScript Object Notation) is the most common format for exchanging data between systems — especially web APIs. It looks similar to Python dictionaries and lists. Python's built-in json module converts between Python objects and JSON strings. Key functions: dumps = dict → string, loads = string → dict, dump = write to file, load = read from file. The "s" suffix stands for "string".

Python → JSON with dumps()

Python True/False/None automatically become JSON true/false/null. Use indent=2 for human-readable output.

dumps.py
import json
data = {{"name": "Alice", "age": 28, "skills": ["Python", "SQL"], "active": True}}

print(json.dumps(data))             # compact
print(json.dumps(data, indent=2))   # pretty
▶ Output
{{"name": "Alice", "age": 28, "skills": ["Python", "SQL"], "active": true}}
{{
  "name": "Alice",
  "age": 28,
  "skills": [
    "Python",
    "SQL"
  ],
  "active": true
}}

JSON → Python with loads()

loads() parses a JSON string into Python objects. This is what you use when you get a response from a web API.

loads.py
import json
js = '{"city": "London", "temp": 12.5, "rain": true}'
w = json.loads(js)
print(type(w))          # dict
print(w["city"])
print(w["rain"])        # JSON true → Python True
▶ Output

London
True

Reading and Writing JSON Files

json.dump() writes to a file; json.load() reads from one. This is the standard way to save configuration or persistent data between program runs.

files.py
import json
cfg = {{"theme": "dark", "font": 14}}
with open("config.json", "w") as f:
    json.dump(cfg, f, indent=2)

with open("config.json") as f:
    loaded = json.load(f)
print(loaded["theme"])
▶ Output
dark
Not all Python objects are JSON-serialisable. datetime objects, sets, and custom class instances need special handling — use default=str as a quick fallback.

🧠 Quick Check

Which function converts a Python dict to a JSON string?

json.load()
json.dumps()
json.encode()
json.stringify()

Tags

jsondumpsloadsjson fileserializedeserializeAPI