Node.js解析记录集输出

时间:2019-03-05 19:28:18

标签: node.js json parsing

我是初学者,正在学习Node.js,从未遇到过解析json数组的事情。我已经遵循了这个脚本。

最后,我记录结果变量的值:

var json = '{
    "recordsets": [
        [
            {
                "@responseMessage": "OK"
            }
        ]
    ],
    "recordset": [
        {
            "responseMessage": "OK"
        }
    ],
    "output": {},
    "rowsAffected": [
        1
    ]
}';
obj = JSON.parse(json);

console.log(obj.count);
console.log(obj.responseMessage);

app.post('/loginUser', function (req, res) {
var pum = req.body.pum; //user mail or user phone 
var pw = req.body.pw; //user password
sql.connect(config, function (err) {
    if (err) console.log(err);
    var request = new sql.Request();
    let query = "DECLARE @responseMessage nvarchar(2) EXEC [dbo].[LoginUser] @pum = N'" + pum + "', @pPwd = N'" + pw + "', @responseMessage = @responseMessage OUTPUT SELECT @responseMessage as N'@responseMessage'"; //SP in a SQL Server
    request.query(query, function (err, recordset) {
        if (err) {
            console.log(err);
            sql.close();
        }
        sql.close();
        res.json(recordset);
        console.log("IP :" + req.ip + "\n");
        console.log(recordset);
    });
});

});

我需要解析声明为@responseMessage输出的存储过程。我的存储过程SQL Server代码在这里:

USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[LoginUser]
    @pum NVARCHAR(254), --user mail or userphone
    @pPwd NVARCHAR(50),
    @responseMessage NVARCHAR(250)='' OUTPUT
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @userID INT
    IF EXISTS (SELECT TOP 1 UserID FROM [dbo].[User] WHERE (userphone=@pum or usermail=@pum))
    BEGIN
        SET @userID=(SELECT UserID FROM [dbo].[User] WHERE (userphone=@pum or usermail=@pum) AND PasswordHash=HASHBYTES('SHA2_512', @pPwd+CAST(Salt AS NVARCHAR(36))))
       IF(@userID IS NULL)
            SET @responseMessage='IP' --'Incorrect password'
       ELSE 
           SET @responseMessage='OK' --'User successfully logged in'
    END
    ELSE
       SET @responseMessage='IL' --'Invalid login'
END

Node.js输出:

{ recordsets: [ [ [Object] ] ],
  recordset: [ { '@responseMessage': 'OK' } ],
  output: {},
  rowsAffected: [ 1 ] }

编辑解决方案:

选项1:

var myRS = recordset;
console.log(myRS.recordsets[0][0]["@responseMessage"]);

选项2: 以正则表达式为例:https://rubular.com/r/jXv0bcaIkPzVOD

0 个答案:

没有答案