How to serialize SqlAlchemy result to JSON?

后端 未结 27 1950
说谎
说谎 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条回答
  •  眼角桃花
    2020-11-22 10:18

    The AlchemyEncoder is wonderful but sometimes fails with Decimal values. Here is an improved encoder that solves the decimal problem -

    class AlchemyEncoder(json.JSONEncoder):
    # To serialize SQLalchemy objects 
    def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            model_fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                print data
                try:
                    json.dumps(data)  # this will fail on non-encodable values, like other classes
                    model_fields[field] = data
                except TypeError:
                    model_fields[field] = None
            return model_fields
        if isinstance(obj, Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)
    

提交回复
热议问题