Last active
December 9, 2016 19:57
-
-
Save dsuch/6285898 to your computer and use it in GitHub Desktop.
Converting SQLAlchemy objects to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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