Working with JSON
Save and load structured data
Lists and dictionaries disappear when your program ends. JSON lets you save them to a file and load them back later, exactly as they were. It's also the format almost every web API uses to send data.
What is JSON?
JSON (JavaScript Object Notation) is a text format for structured data. It looks almost exactly like Python dictionaries and lists, and nearly every programming language and tool can read it.
{
"name": "Ana",
"age": 29,
"is_active": true,
"skills": ["python", "sql"],
"manager": null
}| Feature | Python | JSON |
|---|---|---|
| Dictionary / object | {"a": 1} | {"a": 1} |
| List / array | [1, 2] | [1, 2] |
| String | "hi" or 'hi' | "hi" (double quotes only) |
| Booleans | True / False | true / false |
| Nothing | None | null |
The json module
Python's built-in json module has four functions. The ones ending in s work with strings, and the others work with files.
| Feature | Direction | Works with |
|---|---|---|
| json.dump() | Python → JSON | File |
| json.load() | JSON → Python | File |
| json.dumps() | Python → JSON | String |
| json.loads() | JSON → Python | String |
Saving to a JSON file
import json
students = [
{"name": "Ana", "score": 91},
{"name": "Ben", "score": 78},
]
with open("students.json", "w", encoding="utf-8") as f:
json.dump(students, f, indent=2, ensure_ascii=False)indent=2spreads the output over several lines so humans can read it.ensure_ascii=Falsekeeps accents and emoji as they are instead of escape codes.
Loading from a JSON file
import json
with open("students.json", encoding="utf-8") as f:
students = json.load(f)
print(len(students), "students loaded")
print(students[0]["name"]) # AnaWhat you get back is ordinary Python lists and dictionaries, so everything from the Nested data lesson works on it.
Converting to and from strings
json.dumps() and json.loads() convert between Python data and JSON text without touching a file. This is useful when data comes from or goes to an API.
import json
data = {"role": "user", "content": "Hi"}
text = json.dumps(data)
print(text) # {"role": "user", "content": "Hi"}
print(type(text)) # <class 'str'>
back = json.loads(text)
print(back["content"]) # HiReal example: saving progress
A common pattern is to load saved data if it exists, and start fresh if it doesn't.
import json
from pathlib import Path
SAVE_FILE = Path("scores.json")
if SAVE_FILE.exists():
scores = json.loads(SAVE_FILE.read_text(encoding="utf-8"))
else:
scores = {}
scores["Ana"] = scores.get("Ana", 0) + 10
SAVE_FILE.write_text(json.dumps(scores, indent=2), encoding="utf-8")
print(scores)What JSON can't store
JSON only understands dictionaries, lists, strings, numbers, booleans, and null. Sets, tuples, dates, and your own objects need converting first.
import json
tags = {"python", "ai"}
# json.dumps(tags) # TypeError: Object of type set is not JSON serializable
print(json.dumps(sorted(tags))) # ["ai", "python"]Common mistakes
- Mixing up
dump/load(files) withdumps/loads(strings). - Writing JSON by hand with single quotes or a trailing comma. Both are invalid in JSON and cause a
JSONDecodeError. - Trying to save sets or custom objects without converting them first.
What's next?
With files and JSON, your programs can remember data between runs. Next, you'll work with other file formats like CSV and Excel using the pandas library.