The result of serializing the SqlAlchemy is a JSON string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.