如何获得二级Json值

时间:2016-10-01 21:44:45

标签: javascript jquery json

我试图在响应中迭代第二级json值。

这是Json的一个样本:

  {

  "Links": {},

 "Items": [

  {

  "WebId": "A0EUfSms148rEStZ8_fh",

  "Name": "AA to Slurry ",

  "Path": "klj",

  "Links": {

    "Source": ""

  },

  "Items": [

    {

      "Timestamp": "2016-08-21T05:14:27.0180053Z",

      "Value": 0.0154830571,

      "UnitsAbbreviation": "%",

      "Good": true,

      "Questionable": false,

      "Substituted": false

    },

    {

      "Timestamp": "2016-08-21T05:14:30Z",

      "Value": 0.0155982981,

      "UnitsAbbreviation": "%",

      "Good": true,

      "Questionable": false,

      "Substituted": false

    },

    {

      "Timestamp": "2016-08-21T05:14:30Z",

      "Value": 0.0155982981,

      "UnitsAbbreviation": "%",

      "Good": true,

      "Questionable": false,

      "Substituted": false

    },

    {

      "Timestamp": "2016-08-21T05:14:33.024002Z",

      "Value": 0.0155704552,

      "UnitsAbbreviation": "%",


  "Items": [

{

  "WebId": "A0EUfSms148rEStZ8_fh",

  "Name": “Slurry ",

  "Path": "klj",

  "Links": {

    "Source": ""

  },

  "Items": [

    {

      "Timestamp": "2016-08-21T05:14:27.0180053Z",

      "Value": 0.0154830571,

      "UnitsAbbreviation": "%",

      "Good": true,

      "Questionable": false,

      "Substituted": false

    },

    {

      "Timestamp": "2016-08-21T05:14:30Z",

      "Value": 0.0155982981,

      "UnitsAbbreviation": "%",

      "Good": true,

      "Questionable": false,

      "Substituted": false

    },

    {

      "Timestamp": "2016-08-21T05:14:30Z",

      "Value": 0.0155982981,

      "UnitsAbbreviation": "%",

      "Good": true,

      "Questionable": false,

      "Substituted": false

    },

    {

      "Timestamp": "2016-08-21T05:14:33.024002Z",

      "Value": 0.0155704552,

      "UnitsAbbreviation": "%",

这是我到目前为止只返回名称的代码:

  var feat = resp.Items,
        tableData = [];

    // Iterate over the JSON object
    for (var i = 0, len = feat.length; i < len; i++) {
        tableData.push({
            "name": feat[i].Name,
            "Timestamp": feat[i].Timestamp,
            "value": feat[i].Items.Value,

        });
    }

因此,在此示例中,此示例tabledata理想情况下如下所示:

name        | Timestamp | value
AA to Slurry  
AA to Slurry
AA to Slurry
AA to Slurry
AA to Slurry
AA to Slurry 
Slurry 
Slurry
Slurry
Slurry
Slurry
Slurry

使用第二级&#34; Items&#34;的相应时间戳和值。现在,我得到的是名称值如何获取名称然后迭代第二级项目?

1 个答案:

答案 0 :(得分:3)

我认为您的问题是您的子Items数组是直接访问的。 (feat[i].Items.Value)而你应该遍历第二个数组。我把这段代码放在一起让你开始,它循环遍历json中的项目,然后循环遍历第一个数组中每个项目内的项目。

json.Items.forEach(function(item){
  item.Items.forEach(function(subItem){
    tableData.push({
      'name':item.Name,
      'timestamp':item.TimeStamp,
      'value':subItem.Value
    });
  });
});