How to serialize SqlAlchemy result to JSON?

后端 未结 27 1879
说谎
说谎 2020-11-22 09:59

Django has some good automatic serialization of ORM models returned from DB to JSON format.

How to serialize SQLAlchemy query result to JSON format?

I tried

27条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:27

    install simplejson by pip install simplejson and the create a class

    class Serialise(object):
    
        def _asdict(self):
            """
            Serialization logic for converting entities using flask's jsonify
    
            :return: An ordered dictionary
            :rtype: :class:`collections.OrderedDict`
            """
    
            result = OrderedDict()
            # Get the columns
            for key in self.__mapper__.c.keys():
                if isinstance(getattr(self, key), datetime):
                    result["x"] = getattr(self, key).timestamp() * 1000
                    result["timestamp"] = result["x"]
                else:
                    result[key] = getattr(self, key)
    
            return result
    

    and inherit this class to every orm classes so that this _asdict function gets registered to every ORM class and boom. And use jsonify anywhere

提交回复
热议问题