Skip to content

Instantly share code, notes, and snippets.

@exit99
Created February 20, 2015 15:52
Show Gist options
  • Save exit99/2975db1402b773898b50 to your computer and use it in GitHub Desktop.
Save exit99/2975db1402b773898b50 to your computer and use it in GitHub Desktop.
Json encode sqlalchemy models
class AlchemyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj.__class__, DeclarativeMeta):
# a SQLAlchemy class
fields = {}
for field in [x for x in dir(obj)
if not x.startswith('_') and x != 'metadata']:
data = obj.__getattribute__(field)
if field == "discount": data = unicode(data)
try:
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