Sometimes, we want to serialize SQLAlchemy result to JSON with Python.
In this article, we’ll look at how to serialize SQLAlchemy result to JSON with Python.
How to serialize SQLAlchemy result to JSON with Python?
To serialize SQLAlchemy result to JSON with Python, we can add a method to return the model class content as a dict.
For instance, we weite
class User:
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
to create the User
class that has the as_dict
method that returns a dict that has all the properties in the dict.
The instance property names are the keys and the instance property values are values.
Conclusion
To serialize SQLAlchemy result to JSON with Python, we can add a method to return the model class content as a dict.