gpt4 book ai didi

javascript - 从 json 响应中解析动态 json 对象

转载 作者:行者123 更新时间:2023-11-28 18:44:18 24 4
gpt4 key购买 nike

我有这个动态 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);
});
}
}
});

但不幸的是,它返回了一个错误(请参阅下文)

Uncaught TypeError: Cannot read property 'status' of undefined

有什么帮助、想法、建议、推荐、线索吗?

最佳答案

从您的回复结构来看,以下内容可行

$.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

编辑:

在评论中澄清并假设将有任何单个 key 之后下面可以工作

$.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);
});

关于javascript - 从 json 响应中解析动态 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35645688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com