Skip to content

JSON Serialization

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

diagram what a view is allowed to return mermaid
Flask accepts several shapes and converts each into a Response. A dict or a list becomes JSON automatically, so jsonify is no longer required for the common case. A tuple lets you set the status and headers without building a Response by hand. Anything else has to be a Response already.

JSON supports:

  • strings
  • numbers
  • booleans
  • null
  • arrays
  • objects

In Python terms:

  • str, int, float, bool, None
  • list/tuple
  • dict

Common non-serializable types:

  • datetime
  • database model objects
  • Decimal

You must convert them.

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

For larger APIs, people use:

  • Marshmallow
  • Pydantic

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

Try to keep error responses consistent:

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

Consistency makes frontend/mobile clients much easier to build.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading