Convert sql object to valid Json string in node.js - Azure

前端 未结 4 861
轻奢々
轻奢々 2021-01-07 03:57

We are creating a web service in Azure service using node.js to retrieve data from SQL db. We are using ClearDB to do the same.

While retriving the data its not comm

4条回答
  •  孤城傲影
    2021-01-07 04:37

    i built a function to convert the query to JSON, its working very well:

    i use Date columns from several tables, it is required to be string (which is fine for me), so these columns will have to be called/contain "Date", other data columns will be float .2f format.

    def conv_func(data, columns):
        gen_dict={}
        for j, row in enumerate(data):
            dict = {}
            for col in columns:
                dict[col] = ''
            for i, val in enumerate(dict.keys()):
                if 'Date' in val:
                    dict[val]=str(row[i])
                else:
                    try:
                        dict[val] = round((row[i]),2)
                    except:
                        dict[val]=(row[i])
            gen_dict[j] = dict
        return list(gen_dict.values())
    

    and use the same columns list for the query itself:

    def get_tools():
        cur = set_connection()
        columns=['Col1','Col2','Col3']
        columnsQuery=','.join(columns)
        cur.execute(f"SELECT {columnsQuery} FROM [MyTable] ORDER BY [Col1] DESC")
        data = cur.fetchall()
        return {'success': True, 'data': conv_func(data,columns)}
    

提交回复
热议问题