Created
February 20, 2015 15:52
-
-
Save exit99/2975db1402b773898b50 to your computer and use it in GitHub Desktop.
Json encode sqlalchemy models
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
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