How to serialize SqlAlchemy result to JSON?

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

    When using sqlalchemy to connect to a db I this is a simple solution which is highly configurable. Use pandas.

    import pandas as pd
    import sqlalchemy
    
    #sqlalchemy engine configuration
    engine = sqlalchemy.create_engine....
    
    def my_function():
      #read in from sql directly into a pandas dataframe
      #check the pandas documentation for additional config options
      sql_DF = pd.read_sql_table("table_name", con=engine)
    
      # "orient" is optional here but allows you to specify the json formatting you require
      sql_json = sql_DF.to_json(orient="index")
    
      return sql_json
    
    

提交回复
热议问题