在KeyPair基础上的Jquery中循环json数据

时间:2015-07-17 11:12:09

标签: java jquery html json spring

下面的嗨大家是我从服务器获得的回复。我试图基于密钥循环它,不幸的是我没有成功。

{"metricsLevelList": [{
"levelName": "Account1Name",
"levelId": 1,
"metrics":    [
        {
     "value": "80",
     "greenZoneStart": "90",
     "greenZoneEnd": "100",
     "yellowZoneStart": "60",
     "yellowZoneEnd": "90",
     "redZoneStart": "0",
     "redZoneEnd": "60",
     "metricsType": "Dial",
     "metricsName": "FTR Deliverables"
  },
        {
     "value": "0",
     "greenZoneStart": "90",
     "greenZoneEnd": "100",
     "yellowZoneStart": "60",
     "yellowZoneEnd": "90",
     "redZoneStart": "0",
     "redZoneEnd": "60",
     "metricsType": "Dial",
     "metricsName": "OTD Deliverables"
  },
        {
     "value": "0",
     "greenZoneStart": "0",
     "greenZoneEnd": "5",
     "yellowZoneStart": "5",
     "yellowZoneEnd": "15",
     "redZoneStart": "15",
     "redZoneEnd": "100",
     "metricsType": "Dial",
     "metricsName": "% Defect Rejection"
  },
        {
     "value": null,
     "greenZoneStart": null,
     "greenZoneEnd": null,
     "yellowZoneStart": null,
     "yellowZoneEnd": null,
     "redZoneStart": null,
     "redZoneEnd": null,
     "metricsType": null,
     "metricsName": null
  },
        {
     "value": "0",
     "greenZoneStart": "90",
     "greenZoneEnd": "100",
     "yellowZoneStart": "70",
     "yellowZoneEnd": "90",
     "redZoneStart": "0",
     "redZoneEnd": "70",
     "metricsType": "Dial",
     "metricsName": "CSAT (% VoC)"
  }
]
}]}

这里我必须在metrics的另一个循环(具有度量内容)中循环metricsLevelList(其中我将有不同的级别名称)。有人请帮帮我。

2 个答案:

答案 0 :(得分:0)

您可以使用以下循环来迭代嵌套对象(假设您的json存储在名为jsonDemo的变量中):

function loop(obj) {
    $.each(obj, function(key, val) {
        if(val && typeof val === "object") { // object, call recursively
            console.log(" "); 
            loop(val);
        } else {
            console.log(key + "-->" + obj[key]); 
        }
    });
}

loop(jsonDemo);

请参阅小提琴:" http://jsfiddle.net/pgo637dj/"

说明:这将迭代对象的所有键并检查每个键是否还是一个对象,如果是,它将递归调用它,否则它将被显示。

答案 1 :(得分:0)

我经过大量的追踪和错误后得到了答案

var responseEle =${response};
var importantObject = responseEle.metricsLevelList[0];
for (var item in importantObject) {
var theDate = item; //the KEY
var theNumber = importantObject[item]; //the VALUE
if(item =='metrics')
{
$.each(theNumber, function(i, newItem){

});
}
}