【问题标题】:Accessing elements in JSON for nodejs为nodejs访问JSON中的元素
【发布时间】:2019-09-04 09:48:01
【问题描述】:

首先我对 node/JSON 非常陌生,所以请在阅读时考虑到这一点。

此代码的目的是从 SQL Server 数据库中获取数据,并能够访问它提取的元素。例如,它会提取数千个父帐户 ID,而我只想访问其中一个。

我几乎一整天都在浏览论坛,试图从我的 nodejs 函数访问 JSON 元素,每次我尝试访问其中一个元素时,都会遇到“未定义”错误。作为最后的手段,我在这里。

我检查了几次,发现记录集已被解析,似乎正在被解析。

下面是我的代码,后面是一个非常小的 JSON 代码示例。

我已经评论了我的错误所在。

function getEmp() {
    var conn = new sql.ConnectionPool(dbConfig);
    var req = new sql.Request(conn);

    conn.connect(function (err) {
        if (err) {
            console.log(err);
            return;
        }
        req.query("SELECT * FROM parentaccount Where accountname like 'Titan%' FOR JSON PATH", function (err, recordset) {
            if (err) {
                console.log(err);
            }
            else {
                const Test1 = recordset[0].ParentAccountId; //error here
                console.log(Test1);
            }
            conn.close();
        })
    })
}

getEmp();





//EXAMPLE JSON
{ recordsets: [ [ [Object] ] ],
recordset:   
[ { 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B':
'[{"ParentAccountId":4241411,"AccountName":"Titan"} ],
output: {},
rowsAffected: [ 3 ] }



ERROR:
TypeError: Cannot read property 'ParentAccountId' of undefined
    at C:\Users\za47387\Desktop\Excel Export Code\test2.js:31:48
    at _query (C:\Users\za47387\node_modules\mssql\lib\base.js:1347:9)
    at Request.tds.Request.err [as userCallback] (C:\Users\za47387\node_modules\mssql\lib\tedious.js:671:15)
    at Request.callback (C:\Users\za47387\node_modules\tedious\lib\request.js:37:27)
    at Connection.endOfMessageMarkerReceived (C:\Users\za47387\node_modules\tedious\lib\connection.js:2104:20)
    at Connection.dispatchEvent (C:\Users\za47387\node_modules\tedious\lib\connection.js:1084:36)
    at Parser.tokenStreamParser.on (C:\Users\za47387\node_modules\tedious\lib\connection.js:914:14)
    at Parser.emit (events.js:189:13)
    at Parser.parser.on.token (C:\Users\za47387\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
    at Parser.emit (events.js:189:13)

【问题讨论】:

  • 只打印记录集。它返回什么?
  • @ParthGhiya 您好 Parth,记录集成功地以 json 格式打印出我的整个查询。但是,我希望只访问一个 json 数据,而不是全部。

标签: sql node.js json parsing


【解决方案1】:

根据您分享的示例,

recordset[0] 未定义,意味着两个选项:

a) 查询的结果未获取任何行。 b) 查询结果的格式与预期不同。

虽然我怀疑 a),但它可以很好地控制输出。请在尝试访问 ParentAccountId 之前运行以下代码。

console.log('output : ', JSON.stringify(recordset, null, 4));

我也将代码重构为:

const Test1 = (Array.isArray(recordset) && 
recordset.length) ? recordset[0].ParentAccountId : null;

这样错误不会导致nodejs进程宕机。

【讨论】:

  • 您好,下面是输出示例。我不得不缩短 json,因为有些信息是机密的。 output : { "recordsets": [ [ { "JSON_F52E2B61-18A1-11d1-B105-00805F49916B": "[{\"ParentAccountId\":1764,\"AccountName\":\"Titan}]" } ]
  • 有一点值得注意,配置中的一个选项将“加密”设置为真。这是数据库的要求,因此不确定在尝试访问它时是否会导致问题。
  • 事实证明我没有得到有效的 JSON。感谢大家的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多