我有一个动态的json对象
{
"servers":[
{
"comp1":{
"server1":{
"status":"boxup",
"ar":{
"0":"95.61"
},
"ip":{
"0":"192.168.1.0"
}
},
"server2":{
"status":"boxup",
"ar":{
"0":"99.5"
},
"ip":{
"0":"192.168.0.1"
}
}
}
},
{
"comp2":{
"server1":{
"status":"boxup",
"ar":{
"0":"88.39"
},
"ip":{
"0":"198.168.1.1"
}
},
"server2":{
"status":"boxup",
"ar":{
"0":"99.88"
},
"ip":{
"0":"192.168.0.1"
}
}
}
},
{
"comp3":{
"server1":{
"status":"none",
"ar":"none",
"ip":"none"
},
"server2":{
"status":"boxup",
"ar":{
"0":"99.97"
},
"ip":{
"0":"http:\/\/122.01.125.107"
}
}
}
},
{
"comp4":{
"server1":{
"status":"boxup",
"ar":{
"0":"95.64"
},
"ip":{
"0":"192.168.1.0"
}
},
"server2":{
"status":"boxup",
"ar":{
"0":"95.65"
},
"ip":{
"0":"192.168.1.2"
}
}
}
},
{
"comp5":{
"server1":{
"status":"boxup",
"ar":{
"0":"71.92"
},
"ip":{
"0":"192.168.1.0"
}
},
"server2":{
"status":"boxup",
"ar":{
"0":"98.89"
},
"ip":{
"0":"192.168.0.3"
}
}
}
}
]
}我试着用$.each解析它(请参阅下面)
$.ajax({
url:"/server-monitoring/load-servers",
type:'post',
dataType:'json',
success:function(e){
if(e.success){
$.each(e.servers,function(index,value){
//log the status from server1 on every comp
console.log(value.server1.status);
});
}
}
});但不幸的是,它返回了一个错误(请参阅下面)。
未定义的TypeError:无法读取未定义的属性“状态”
有什么帮助,想法,建议,推荐,线索吗?
发布于 2016-02-26 07:24:14
从你的反应结构来看,下面的方法会起作用
$.each(e.servers,function(index,value){
//log the status from server1 on every comp
console.log(value['comp'+(index+1)].server1.status);
});给出输出
boxup
boxup
none
boxup
boxup编辑:
在注释中作出澄清,并假设下面有任何一个键可以工作
$.each(e.servers,function(index,value){
//log the status from server1 on every comp
var key = Object.keys(value)[0];
console.log(value[key].server1.status);
}); 发布于 2016-02-26 08:09:59
这个密码怎么样。它还将处理动态键、对象数和动态内部对象。
$.each(data.servers, function(key, value) {
$.each(this,function(key,value){
var parentObj = key;
$.each(value,function(key,value){
console.log(parentObj + '------'+key + '-----'+value.status);
});
});
});这是一个工频
这是输出。
comp1------server1-----boxup
comp1------server2-----boxup
comp2------server1-----boxup
comp2------server2-----boxup
comp3------server1-----none
comp3------server2-----boxup
comp4------server1-----boxup
comp4------server2-----boxup
comp5------server1-----boxup
comp5------server2-----boxup发布于 2016-02-26 07:33:13
通过观察您的JSON结构,我相信每个服务器对象(在服务器数组中)都有一个属性,如comp1、comp2 .这还不清楚。
下面的代码起作用。
var comp = {}; //Just a temp variable to hold dynamic comp property
// value
$.each(v.servers,function(i,v){
//Loop through each key in server object to find first property.
for(var key in v) {
//Make sure its objects own property, just to be safe.
if(v.hasOwnProperty(key)) {
// Fetch our comp (assumed, you can also match key
// and make sure it starts with comp ...
comp = v[key];
break;
}
}
//As we have our comp object, now we can access server1, server2 as shown below
console.log(comp.server1.status);
});希望这能帮上忙!如果你需要进一步的帮助请告诉我.:)
https://stackoverflow.com/questions/35645688
复制相似问题