Serialize SQLAlchemy query results to JSON
Consider you have following model and you want to create super—duper RESTful interface to it.
And here’s one of your views, which returns all the available blog posts:
But unfortunately SQLAlchemy results cannot be serialized to JSON. What to do?
You can spend some time and extend SQLAlchemy’s pickle serializer extension (it’s awkward to extend what’s already extended, but nevermind), however there’s a quicker way. Just make your model class inherit from this base class as well:
simplejson
looks for _asdict()
method when iterating through objects
to be serialized. We can cheat and return our model and its fields as an
ordered dictionary, which is then easily parsed to JSON.
This might not be the quickest method, but certainly is the easiest one.