Nolik Nolik - 1 month ago 7
JSON Question

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?

Answer

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)