Categories
Python Answers

How to serialize SQLAlchemy result to JSON with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *