2016-10-01 85 views
0

我正在嘗試在響應中迭代第二級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, 

     }); 
    } 

所以在這個例子這個例子資料表會非常​​期待像這樣:

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 

與相應的時間戳和值從第二級「我TEMS」。現在我所得到的是名稱值,我如何獲取名稱,然後遍歷二級項目?

+1

你有JSON,還是你有一個對象? – adeneo

+0

@adeneo我有JSON。 – llerdal

+0

@llerdal我們需要確切知道你有'resp'的價值。你是如何將JSON變成JS對象並解析它的? adeneo所說的是,你可能在JavaScript中使用了一個對象而不是JSON,這是一種文本格式的文件,你需要解析成JavaScript。 –

回答

3

我認爲你的問題是你的子項數組正在被直接訪問。 (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 
    }); 
    }); 
});