Skip to content

Instantly share code, notes, and snippets.

@Tjorriemorrie
Created July 23, 2015 13:35
Show Gist options
  • Save Tjorriemorrie/81adbbf1dbd3fe4e63b6 to your computer and use it in GitHub Desktop.
Save Tjorriemorrie/81adbbf1dbd3fe4e63b6 to your computer and use it in GitHub Desktop.
Flask-SqlAlchemy encoder
# refer http://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json#answer-31569287
from sqlalchemy.ext.declarative import DeclarativeMeta
from flask import json
class AlchemyEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o.__class__, DeclarativeMeta):
data = {}
fields = o.__json__() if hasattr(o, '__json__') else dir(o)
for field in [f for f in fields if not f.startswith('_') and f not in ['metadata', 'query', 'query_class']]:
value = o.__getattribute__(field)
try:
json.dumps(value)
data[field] = value
except TypeError:
data[field] = None
return data
return json.JSONEncoder.default(self, o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment