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/)
You could just output your object as a dict:
And then you use User.as_dict() to serialize your object.
As explained in Convert sqlalchemy row object to python dict
Custom serialization and deserialization.
"from_json" (class method) builds a Model object based on json data.
"deserialize" could be called only on instance, and merge all data from json into Model instance.
"serialize" - recursive serialization
__write_only__ property is needed to define write only properties ("password_hash" for example).
I thought I'd play a little code golf with this one.
FYI: I am using automap_base since we have a separately designed schema according to business requirements. I just started using SQLAlchemy today but the documentation states that automap_base is an extension to declarative_base which seems to be the typical paradigm in the SQLAlchemy ORM so I believe this should work.
It does not get fancy with following foreign keys per Tjorriemorrie's solution, but it simply matches columns to values and handles Python types by str()-ing the column values. Our values consist Python datetime.time and decimal.Decimal class type results so it gets the job done.
Hope this helps any passers-by!
My take utilizing (too many?) dictionaries:
Running with flask (including jsonify) and flask_sqlalchemy to print outputs as JSON.
Call the function with jsonify(serialize()).
Works with all SQLAlchemy queries I've tried so far (running SQLite3)
You can convert a RowProxy to a dict like this:
Then serialize that to JSON ( you will have to specify an encoder for things like
datetime
values ) It's not that hard if you just want one record ( and not a full hierarchy of related records ).I recommend using a recent surfaced library marshmallow. It allows you to create serializers to represent your model instances with support to relations and nested objects.
Have a look at theier SQLAlchemy Example.