Skip to content

Instantly share code, notes, and snippets.

@Dweez
Last active December 21, 2015 12:39
Show Gist options
  • Save Dweez/7960b9aded6a1006e818 to your computer and use it in GitHub Desktop.
Save Dweez/7960b9aded6a1006e818 to your computer and use it in GitHub Desktop.
Converting SQLAlchemy objects to JSON
# stdlib
from json import dumps
def to_json(model):
""" Returns a JSON representation of an SQLAlchemy-backed object.
"""
json = {}
json['fields'] = {}
json['pk'] = getattr(model, 'id')
for col in model._sa_class_manager.mapper.mapped_table.columns:
json['fields'][col.name] = getattr(model, col.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment