How to serialize SqlAlchemy result to JSON?

后端 未结 27 1875
说谎
说谎 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:07

    def alc2json(row):
        return dict([(col, str(getattr(row,col))) for col in row.__table__.columns.keys()])
    

    I thought I'd play a little code golf with this one.

    FYI: I am using automap_base since we have a separately designed schema according to business requirements. I just started using SQLAlchemy today but the documentation states that automap_base is an extension to declarative_base which seems to be the typical paradigm in the SQLAlchemy ORM so I believe this should work.

    It does not get fancy with following foreign keys per Tjorriemorrie's solution, but it simply matches columns to values and handles Python types by str()-ing the column values. Our values consist Python datetime.time and decimal.Decimal class type results so it gets the job done.

    Hope this helps any passers-by!

提交回复
热议问题