Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create sqlalchemy to json

I have a sqlalchemy result

labels = session.query(
         LabelsData, 
         LabelsData.id, 
         LabelsData.name, 
         LabelsData.color
         ).filter(LabelsData.deleted==False).all()

And I want convert this result to JSON, but how I can do it?

like image 298
Nolik Avatar asked Feb 17 '13 10:02

Nolik


People also ask

How do you serialize a SQLAlchemy model?

If you want SQLAlchemy model to become serializable, add SerializerMixin in class definition: from sqlalchemy_serializer import SerializerMixin class SomeModel(db. Model, SerializerMixin): ... Note that method or a function should have no arguments except self, in order to let serializer call it without hesitations.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

Is SQLAlchemy a ORM?

SQLAlchemy is a library that facilitates the communication between Python programs and databases. Most of the times, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.


4 Answers

It looks like your LabelsData object is a SQLAlchemy model. You need to serialize it before dumping it to JSON. Here's a short example that extracts all the columns from your LabelsData object and converts the results of your query to JSON:

from json import dumps
from sqlalchemy.orm import class_mapper

def serialize(model):
  """Transforms a model into a dictionary which can be dumped to JSON."""
  # first we get the names of all the columns on your model
  columns = [c.key for c in class_mapper(model.__class__).columns]
  # then we return their values in a dict
  return dict((c, getattr(model, c)) for c in columns)

# we can then use this for your particular example
serialized_labels = [
  serialize(label)
  for label in session.query(LabelsData).filter(LabelsData.deleted == False)
]
your_json = dumps(serialized_labels)
like image 55
mtth Avatar answered Oct 22 '22 20:10

mtth


from collections import OrderedDict

class DictSerializable(object):
    def _asdict(self):
        result = OrderedDict()
        for key in self.__mapper__.c.keys():
            result[key] = getattr(self, key)
        return result

From here and appearing to require simplejson. Hope that helps...

UPDATE: on a second look, it's a dictionary, which you can dump by any of the json modules in python.

like image 28
hd1 Avatar answered Oct 22 '22 19:10

hd1


Looks like sqlalchemy already has one http://docs.sqlalchemy.org/en/latest/core/serializer.html

from sqlalchemy.ext.serializer import loads, dumps
metadata = MetaData(bind=some_engine)
Session = scoped_session(sessionmaker())

# ... define mappers

query = Session.query(MyClass).filter(MyClass.somedata=='foo').order_by(MyClass.sortkey)

# pickle the query
serialized = dumps(query)

# unpickle.  Pass in metadata + scoped_session
query2 = loads(serialized, metadata, Session)

print query2.all()
like image 26
Nande Avatar answered Oct 22 '22 20:10

Nande


This blog post provided the solution I went with: http://blogs.gnome.org/danni/2013/03/07/generating-json-from-sqlalchemy-objects/

The strategy used was to include a .todict method directly to a Base mixin which iterates over the parent class's sqlalchemy columns.

Alternatively, Nande's approach (https://stackoverflow.com/a/19602809/837575) to use sqlalchemy.ext.serializer works well if you're trying to serialize data over the wire but don't necessarily need it as json.

like image 38
mekarpeles Avatar answered Oct 22 '22 19:10

mekarpeles