Skip to content

Instantly share code, notes, and snippets.

@dsuch
Last active December 9, 2016 19:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsuch/6285898 to your computer and use it in GitHub Desktop.
Save dsuch/6285898 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)
return dumps([json])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment