Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried jsonpickle.encode
but it encodes query object itself.
I tried json.dumps(items)
but it returns
TypeError: <Product('3', 'some name', 'some desc')> is not JSON serializable
Is it really so hard to serialize SQLAlchemy ORM objects to JSON /XML? Isn't there any default serializer for it? It's very common task to serialize ORM query results nowadays.
What I need is just to return JSON or XML data representation of SQLAlchemy query result.
SQLAlchemy objects query result in JSON/XML format is needed to be used in javascript datagird (JQGrid http://www.trirand.com/blog/)
Here is a solution that lets you select the relations you want to include in your output as deep as you would like to go. NOTE: This is a complete re-write taking a dict/str as an arg rather than a list. fixes some stuff..
so for an example using person/family/homes/rooms... turning it into json all you need is
A more detailed explanation. In your model, add:
The
str()
is for python 3 so if using python 2 useunicode()
. It should help deserialize dates. You can remove it if not dealing with those.You can now query the database like this
First()
is needed to avoid weird errors.as_dict()
will now deserialize the result. After deserialization, it is ready to be turned to jsonYou can use introspection of SqlAlchemy as this :
Get inspired from an answer here : Convert sqlalchemy row object to python dict
I know this is quite an older post. I took solution given by @SashaB and modified as per my need.
I added following things to it:
My code is as follows:
Hope it helps someone!
It is not so straighforward. I wrote some code to do this. I'm still working on it, and it uses the MochiKit framework. It basically translates compound objects between Python and Javascript using a proxy and registered JSON converters.
Browser side for database objects is db.js It needs the basic Python proxy source in proxy.js.
On the Python side there is the base proxy module. Then finally the SqlAlchemy object encoder in webserver.py. It also depends on metadata extractors found in the models.py file.
While the original question goes back awhile, the number of answers here (and my own experiences) suggest it's a non-trivial question with a lot of different approaches of varying complexity with different trade-offs.
That's why I built the SQLAthanor library that extends SQLAlchemy's declarative ORM with configurable serialization/de-serialization support that you might want to take a look at.
The library supports:
dict
password
value, but never include an outbound one)You can check out the (I hope!) comprehensive docs here: https://sqlathanor.readthedocs.io/en/latest
Hope this helps!