简体   繁体   中英

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

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 comming in a proper JSON format. How can we convert the result sql object to JSON string.

Below is my code.

app.get('/android', function(request, response) {
    pool.getConnection(function(err, connection) {
        if(err) { handleErrorResponse(err, response); return; }
            var sql = "select projectname from taggedemployee where empname='test@hotmail.com' and tagflag='accepted'"
        connection.query(sql, {}, function(err, results) {
              connection.release(); // always put connection back in pool after last query
          if(err) { handleErrorResponse(err, response); return;  }
                var proj = JSON.stringify(results);
                console.log(proj);
                console.log(proj[0].projectname);
                 for(var myKey in proj) {
                    console.log("key:"+ myKey+", value:"+proj[myKey]);
                 }
          response.setHeader('Content-Type', 'application/json');
          response.status(200).send(JSON.stringify(results) );

        });
    });
});

I cant manipulate the JSON string the returning string is

[{projectname: "Dominos"}]

I tried JSON.stringify but no luck. Please help me to fix this issue

You don't need JSON.stringify() actually. results is already your javascript object, which represents array of json objects. Just use

console.log(results[0].projectname);

The JavaScript Object or Array is JSON, and you need to convert a JSON string to a JavaScript Object thru the function eval or JSON.parse . Please refer to http://www.json.org/js.html .

The response from the SQL service is JSON - as you have shown. You need to use JSON.parse() to parse the JSON into an object. Something like:

app.get('/android', function(request, response) {
    pool.getConnection(function(err, connection) {
        if(err) { handleErrorResponse(err, response); return; }
            var sql = "select projectname from taggedemployee where empname='test@hotmail.com' and tagflag='accepted'"
        connection.query(sql, {}, function(err, results) {
              connection.release(); // always put connection back in pool after last query
          if(err) { handleErrorResponse(err, response); return;  }
                var proj = JSON.parse(response);
                console.log(proj);
          response.setHeader('Content-Type', 'application/json');
          response.status(200).send(results);

        });
    });
});

JSON.stringify is used to convert an object into a JSON string. JSON.parse is used to convert a JSON string into an object.

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM