Node.js JSON嵌套数组对象访问

时间:2018-02-18 22:50:02

标签: javascript arrays json node.js express

我正在使用SONARQUBE中的API调用构建一个GETS JSON响应的应用程序。

使用节点js如何从以下JSON对象访问 duplicated_lines 的值。

我尝试了以下但总是未定义。有没有支持探索这些对象的库?

代码

var subrequest = unirest("GET",queryUrl);

subrequest.end(function (resXX) {
  if (resXX.error);
    for (var key in resXX) { 
      if (resXX.hasOwnProperty(key)) {
        console.log("Checking the id " + resXX[key].msr.duplicated_lines);
      }
    }
});

JSON

[
  {
    "id": 1933853,
    "uuid": "XXXXXXXXXXXXXX",
    "key": "XXXXXXXXXXXX",
    "name": "XXXXXXX",
    "scope": "PRJ",
    "qualifier": "TRK",
    "date": "2018-02-16T08:07:55-0500",
    "creationDate": "2017-09-20T09:50:05-0400",
    "lname": "XXXXXXXX",
    "version": "15",
    "msr": [
      {
        "key": "duplicated_lines",
        "val": 926192,
        "frmt_val": "926,192"
      },
      {
        "key": "bugs",
        "val": 7467,
        "frmt_val": "7,467"
      },
      {
        "key": "ncloc",
        "val": 1369829,
        "frmt_val": "1,369,829"
      },
      {
        "key": "code_smells",
        "val": 22677,
        "frmt_val": "22,677"
      },
      {
        "key": "vulnerabilities",
        "val": 95,
        "frmt_val": "95"
      }
    ]
  }
]

3 个答案:

答案 0 :(得分:4)

我对您正在访问的API一无所知,并且在没有任何其他信息的情况下您的代码很难解释。但是msr是一个数组,因此您需要使用索引访问其中的对象:

resXX[key].msr.forEach(m => {
    if (m.key === 'duplicated_lines') {
        console.log('Checking the id ' + m.val);
    }
});

答案 1 :(得分:0)

  

我尝试过以下但总是未定义

因为您在访问时尝试将对象value用作key

试用这一行代码:

var duplicateData = jsonObj[0].msr.filter(item => item.key == 'duplicated_lines');

工作演示

var jsonObj = [
  {
    "id": 1933853,
    "uuid": "XXXXXXXXXXXXXX",
    "key": "XXXXXXXXXXXX",
    "name": "XXXXXXX",
    "scope": "PRJ",
    "qualifier": "TRK",
    "date": "2018-02-16T08:07:55-0500",
    "creationDate": "2017-09-20T09:50:05-0400",
    "lname": "XXXXXXXX",
    "version": "15",
    "msr": [
      {
        "key": "duplicated_lines",
        "val": 926192,
        "frmt_val": "926,192"
      },
      {
        "key": "bugs",
        "val": 7467,
        "frmt_val": "7,467"
      },
      {
        "key": "ncloc",
        "val": 1369829,
        "frmt_val": "1,369,829"
      },
      {
        "key": "code_smells",
        "val": 22677,
        "frmt_val": "22,677"
      },
      {
        "key": "vulnerabilities",
        "val": 95,
        "frmt_val": "95"
      }
    ]
  }
];

var duplicateData = jsonObj[0].msr.filter(item => item.key == 'duplicated_lines');

console.log(duplicateData);

答案 2 :(得分:0)

这是一个迭代响应JSON数组的单行解决方案

resXX.forEach(item => item.msr.forEach(v => v['key']==='duplicated_lines' && console.log(`Checking the id ${v['val']}`)))