0

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

4

1 回答 1

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

于 2013-07-15T13:25:48.020 回答