JSON
{
"AA1 1AA":{
"ExchangeCode":"XXX",
"ExchangeName":"XXXXX",
"Options":{
"10":{
"Preference":"Preference 1",
"Option 1":123,
"Option 2":1234,
"Option 3":1234,
"Option 4":1234
},
"20":{ .........
}
}
}
}
AA1 1AA
是一个邮政编码,因此每次请求都会更改。
的jQuery
// var count = 0; is declared in document ready function so that it's global
// JSON response from server is stored in 'data'
var key, count = 0;
for (key in data.Options) {
if(data.Options.hasOwnProperty(key)) {
count++;
}
}
结果只是undefined
答案 0 :(得分:2)
您似乎想要获得第一个元素。你可以这样做:
var count = 0;
for (var k in data) { // only simple cross browser way to get the first property
var obj = data[k];
for (var key in obj) {
count++;
}
break; // no need to go further, we have counted in "AA1 1AA"
}
请注意,我删除了hasOwnProperty
检查:对于JSON解析数据,它完全没用。
请注意,现代浏览器还有其他功能,例如Object.keys