从Nodejs mssql结果解析JSON结果

时间:2017-12-08 11:58:24

标签: javascript json sql-server node.js

我有一个NodeJS应用程序调用MSSqlserver存储过程并返回JSON结果。

如何解析JSON结果以仅获取此值

[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]

JSON结果

{
    recordsets:[
        [
            {
                JSON_F52E2B61-18A1-11d1 - B105-00805F49916B:"[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]"
            }
        ]
    ], 
    recordset:[ 
        {
            JSON_F52E2B61-18A1-11d1 - B105-00805F49916B:"[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]"
        }
    ], 
    output: {}, 
    rowsAffected:[11], 
    returnValue:0
}

的Javascript

var express = require('express'); 
var router = express.Router(); 
var sql = require('mssql'); 

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index',  {title:'Express'}); 
}); 


// SQL Server config
var config =  {
    user:'user', 
    password:'pass', 
    server:'localhost', 
    database:'mydb'
}; 


router.get('/datamart', function (req, res) {

    // connect to your database
    sql.connect(config, function (err) {
        if (err)console.log(err); 

        // create Request object
        var request = new sql.Request(); 

        // query to the database and get the data
        request.execute('dbo.get_datamart', function (err, result) {
            if (err)console.log(err)

            // send data as a response
            console.log(result.recordset);
            res.send(result); 

            sql.close();
        }); 

    }); 

}); 

module.exports = router; 

2 个答案:

答案 0 :(得分:1)

请注意,您的json不是有效的json,我必须手动修复它。你也可以通过递归来升级我的答案,检查数组中是否有数组,依此类推。但这会奏效

results = {
    recordsets:[
        [
            {
                "JSON_F52E2B61-18A1-11d1 - B105-00805F49916B":[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]
            }
        ]
    ], 
    recordset:[ 
        {
            "JSON_F52E2B61-18A1-11d1 - B105-00805F49916B":[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]
        }
    ], 
    output: {}, 
    rowsAffected:[11], 
    returnValue:0
}
let newResults = [];
for(let key in results){
   if(key === "recordsets"){
      results[key].forEach(arr =>{
        arr.forEach(obj =>{
            Object.keys(obj).forEach((key) =>{
              newResults.push(obj[key])
            })
          });
      })
   }
}
console.log(newResults)

答案 1 :(得分:0)

有比@amit 回答更简单的方法。

bootstrap.yml

这样你就不必使用 FOR JSON PATH