Python for AIPython for AI
Building Programs

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.

user.json
{
  "name": "Ana",
  "age": 29,
  "is_active": true,
  "skills": ["python", "sql"],
  "manager": null
}
FeaturePythonJSON
Dictionary / object{"a": 1}{"a": 1}
List / array[1, 2][1, 2]
String"hi" or 'hi'"hi" (double quotes only)
BooleansTrue / Falsetrue / false
NothingNonenull
How Python values map to JSON values.

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.

FeatureDirectionWorks with
json.dump()Python → JSONFile
json.load()JSON → PythonFile
json.dumps()Python → JSONString
json.loads()JSON → PythonString

Saving to a JSON file

python
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=2 spreads the output over several lines so humans can read it.
  • ensure_ascii=False keeps accents and emoji as they are instead of escape codes.

Loading from a JSON file

python
import json

with open("students.json", encoding="utf-8") as f:
    students = json.load(f)

print(len(students), "students loaded")
print(students[0]["name"])  # Ana

What 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.

python
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"]) # Hi

Real example: saving progress

A common pattern is to load saved data if it exists, and start fresh if it doesn't.

python
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)
Run this a few times. Ana's score keeps growing because it's saved between runs.

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.

python
import json

tags = {"python", "ai"}
# json.dumps(tags)  # TypeError: Object of type set is not JSON serializable

print(json.dumps(sorted(tags)))  # ["ai", "python"]
Tuples are saved as lists, so a tuple comes back as a list when you load it again.

Common mistakes

  • Mixing up dump/load (files) with dumps/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.