jQuery多层JSON

时间:2017-05-28 05:36:12

标签: javascript jquery json javascript-objects

晚上好, 我正在研究一个JSON,我必须解析它以获得我需要的东西。它看起来像这样:

{
    "0":{"ID":"282","WarrSalePrice":"1.00"}
    ,"1":{"ID":"283","WarrSalePrice":"2.00"}
    ,"2":{"ID":"284","WarrSalePrice":"3.00"}
    ,"3":{"ID":"285","WarrSalePrice":"4.00"}
    ,"Totals":{"RowCount":"4","WarrSalePrice":"10.00"}
}

我使用以下代码遍历上面的JSON。

jQuery.each(data, function(index, value){
    alert(value['WarrSalePrice']);    //This get the individual sales prices
});

问题是我需要获取RowCount和TotalSalesPrice。我在这里的逻辑并没有完成它。它告诉我,我的价值如果"未定义"为第5(总计行)。我还需要在调用jQuery.each之前读取RowCount值。因为如果RowCount == 0,则不需要执行jQuery.each。任何人都可以指出我正确的方向。

一切顺利, 乔治

1 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/mvpb1k1r/

检查它是否未定义。

var data = {
    "0":{"ID":"282","WarrSalePrice":"1.00"}
    ,"1":{"ID":"283","WarrSalePrice":"2.00"}
    ,"2":{"ID":"284","WarrSalePrice":"3.00"}
    ,"3":{"ID":"285","WarrSalePrice":"4.00"}
    ,"Totals":{"RowCount":"4","WarrSalePrice":"10.00"}
}

jQuery.each(data, function(index, value){
    if(typeof value['WarrSalePrice'] != "undefined") {
    console.log("WarrSalePrice: " + value['WarrSalePrice']);    //This get the individual sales prices
    }

  if(typeof value['RowCount'] != "undefined") {
    console.log("RowCount: " + value['RowCount']);    //This get the individual sales prices
    }
});