Skip to content

Instantly share code, notes, and snippets.

@satya10x
Created October 11, 2013 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satya10x/6931420 to your computer and use it in GitHub Desktop.
Save satya10x/6931420 to your computer and use it in GitHub Desktop.
from sqlalchemy.ext.declarative import DeclarativeMeta
class AlchemyEncoder(json.JSONEncoder):
def default(self, obj):
print obj.__public__
if isinstance(obj.__class__, DeclarativeMeta):
fields = {}
for field in [x for x in obj.__public__) if not x.startswith('_') and x != 'metadata']:
data = obj.__getattribute__(field)
try:
json.dumps(data)
fields[field] = data
except TypeError:
#If the data could not be encoded, check what its instance is and assign value likewise.
if(isinstance(data,datetime.datetime)):
fields[field] = data.isoformat()
# 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