Skip to content

JSON Serialization

JSON serialization is the process of converting Python data into JSON.

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

Common non-serializable types:

  • datetimedatetime
  • database model objects
  • Decimal

You must convert them.

Serialization strategies

1) Manual dict conversion

python
user_dict = {"id": user.id, "username": user.username}
return user_dict
python
user_dict = {"id": user.id, "username": user.username}
return user_dict

2) Helper method on model

python
class User(db.Model):
    # ...
    def to_dict(self):
        return {"id": self.id, "username": self.username}
python
class User(db.Model):
    # ...
    def to_dict(self):
        return {"id": self.id, "username": self.username}

3) Schema libraries (later)

For larger APIs, people use:

  • Marshmallow
  • Pydantic

This tutorial track keeps it simple: manual to_dict()to_dict() is fine.

Try to keep error responses consistent:

json
{ "error": "validation_error", "message": "Email is required" }
json
{ "error": "validation_error", "message": "Email is required" }

Consistency makes frontend/mobile clients much easier to build.

🧪 Try It Yourself

Exercise 1 – Create a Flask App

Exercise 2 – Dynamic Route

Exercise 3 – Return JSON

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did