I add this anwser as it is a mixture of @mekarpeles and @ hd1. I mean, I did not change the hierarchy of sqlalchemy objects by simply passing in a simple JSONEncoder :
# given that you have Base = declarative_base() class SqlAlchemyModelEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Base): result = OrderedDict() for key in obj.__mapper__.c.keys(): result[key] = getattr(obj, key) return result return json.JSONEncoder.default(self, obj)
If your models use non-serializable classes (e.g. datetime), you should add them to Encoder:
if isinstance(obj, datetime): return obj.isoformat()
And then I use it with jinja2 context filter:
@contextfilter def tojson(ctx, model, *elements, **kw): return json.dumps(model, cls=SqlAlchemyModelEncoder)
Bruno thomas
source share