我有这个JSON响应/
float
我可以使用
获取每个值{
"phweb":{
"name":"PH Web Server",
"cpu":"36.7",
"ram":"33.0",
"hdd":"43.0",
"os":{
"osup":"2 days, 23 hours, 5 minutes and 34 seconds",
"osstat":"0"
},
"apache":{
"apachestat":"0",
"apacheup":"33 days, 2 hours, 9 minutes and 16 seconds"
},
"sql":{
"sqlstat":"0",
"sqlup":"154 days, 2 hours, 16 minutes and 53 seconds"
}
},
"phdbm":{
"name":"PH DBM Server",
"cpu":"15.9",
"ram":"10.7",
"hdd":"23.7",
"os":{
"osup":"2 days, 23 hours, 6 minutes and 21 seconds",
"osstat":"0"
},
"apache":{
"apachestat":"0",
"apacheup":"103 days, 4 hours, 43 minutes and 56 seconds"
},
"sql":{
"sqlstat":"0",
"sqlup":"12 days, 4 hours, 43 minutes and 42 seconds"
}
}
}
如何获取具有子数组值的响应值的值,例如
$.each(response, function(index, value){
console.log(index + " " + value);
});
“phweb”索引的(假设我想从'phweb'的'os'获取'osup'?我如何检查它是否为空或确实存在(以避免错误)?
答案 0 :(得分:1)
首先是JSON object
而不是JSON array
。
您可以使用key
直接访问它。
使用变量名称,例如obj
,并使用.
运算符,并键入该键的值。
在下面的示例中,它是obj.phweb.os
,这意味着obj是具有多个键值对的JSON对象,包括键phweb
,phweb
和os
相同。
请记住:JSON对象具有key value
并且在{}
中包含,而数组具有索引并包裹在[]
中。
var obj = {
"phweb":{
"name":"PH Web Server",
"cpu":"36.7",
"ram":"33.0",
"hdd":"43.0",
"os":{
"osup":"2 days, 23 hours, 5 minutes and 34 seconds",
"osstat":"0"
},
"apache":{
"apachestat":"0",
"apacheup":"33 days, 2 hours, 9 minutes and 16 seconds"
},
"sql":{
"sqlstat":"0",
"sqlup":"154 days, 2 hours, 16 minutes and 53 seconds"
}
},
"phdbm":{
"name":"PH DBM Server",
"cpu":"15.9",
"ram":"10.7",
"hdd":"23.7",
"os":{
"osup":"2 days, 23 hours, 6 minutes and 21 seconds",
"osstat":"0"
},
"apache":{
"apachestat":"0",
"apacheup":"103 days, 4 hours, 43 minutes and 56 seconds"
},
"sql":{
"sqlstat":"0",
"sqlup":"12 days, 4 hours, 43 minutes and 42 seconds"
}
}
}
console.log(obj.phweb.os);