When designing a RESTful Web site, we always want the ORM framework to return a JSON string that can be used directly to the View layer. However, the return result of Sqlalchemy directly uses json.dumps(res)
the error that will be reported TypeError.
Solution Solutions
In fact, as with datetime
the problem of inability to use json.dumps()
serialization, we need to inherit one json.JSONEncoder
.
From sqlalchemy.ext.declarative import Declarativemetaclass alchemyencoder (JSON. Jsonencoder): def default (self, obj): If Isinstance (obj.__class__, Declarativemeta): # an SQLAlchemy Class fields = {} for field in [X for x in dir (obj) if not x.startswith ('_') and x! = ' metadata ']: data = obj.__getattribute__ (field) try:json.dumps (data) # This would F Ail on non-encodable values, like other classes Fields[field] = data except TypeError: # Added processing of datetime if Isinstance (data, Datetime.datetime): Fields[field] = data . Isoformat () elif isinstance (data, datetime.date): Fields[field] = Data.isoforma T () elif isinstance (data, Datetime.timedelta): Fields[field] = (datetime.datetim E.min + data). Time (). Isoformat () Else: Fields[field] = None # a json-encodable dict return fields return JSON. Jsonencoder.default (self, obj)
Reference address: StackOverflow, based on the addition of a simple processing of datatime.
The call is as follows:
c = YourAlchemyClass()print json.dumps(c, cls=AlchemyEncoder)
The result of serializing the SqlAlchemy is a JSON string