Skip to content

Instantly share code, notes, and snippets.

@vcancy
Created May 8, 2018 11:02
Show Gist options
  • Save vcancy/c69807db353f141809211ead2d538634 to your computer and use it in GitHub Desktop.
Save vcancy/c69807db353f141809211ead2d538634 to your computer and use it in GitHub Desktop.
Alchemy object json Encoder
import json
from datetime import datetime
from sqlalchemy.ext.declarative import DeclarativeMeta
class AlchemyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj.__class__, DeclarativeMeta):
# an SQLAlchemy class
fields = {}
for field in [c.key for c in inspect(obj).mapper.column_attrs]:
data = obj.__getattribute__(field)
try:
if isinstance(data, datetime):
data = data.strftime('%Y-%m-%d %H:%M:%S')
json.dumps(data) # this will fail on non-encodable values, like other classes
fields[field] = data
except TypeError:
fields[field] = None
# a json-encodable dict
return fields
return json.JSONEncoder.default(self, obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment