JSON Serialization
JSON serialization is the process of converting Python data into JSON.
flowchart TD A["a view returns …"] --> B["a string"] A --> C["a dict"] A --> D["a list"] A --> E["a tuple"] A --> F["a Response"] B --> B2["200, text/html"] C --> C2["200, application/json"] D --> D2["200, application/json"] E --> E2["(body, status) or (body, status, headers)"] F --> F2["used as-is"] C2 --> G["jsonify() is only needed for older Flask, or to set options"] D2 --> G
What works out of the box
Section titled “What works out of the box”JSON supports:
- strings
- numbers
- booleans
- null
- arrays
- objects
In Python terms:
- str, int, float, bool, None
- list/tuple
- dict
What does NOT serialize automatically
Section titled “What does NOT serialize automatically”Common non-serializable types:
datetime- database model objects
- Decimal
You must convert them.
Serialization strategies
Section titled “Serialization strategies”1) Manual dict conversion
Section titled “1) Manual dict conversion”user_dict = {"id": user.id, "username": user.username}
return user_dict2) Helper method on model
Section titled “2) Helper method on model”class User(db.Model):
# ...
def to_dict(self):
return {"id": self.id, "username": self.username}3) Schema libraries (later)
Section titled “3) Schema libraries (later)”For larger APIs, people use:
- Marshmallow
- Pydantic
This tutorial track keeps it simple: manual to_dict() is fine.
Error response shape (recommended)
Section titled “Error response shape (recommended)”Try to keep error responses consistent:
{ "error": "validation_error", "message": "Email is required" }Consistency makes frontend/mobile clients much easier to build.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading