我有一个 JSON 文件,当页面加载时我必须从该文件中读取数据。我怀疑我的 JSON 结构有问题。 JSONLint 显示它是有效的。所以我一定是使用了错误的方法来访问它。
它基本上是一个对象数组(或者这就是我的想法)。
{"Listings":[
{"Listing1":
{
"agency_code":"BP",
"property_code":"BON1",
"Property_GUID":"6dded624",
"FileNo /":"",
"country":"AUSTRALIA",
"state":"New South Wales",
"subregion /":""
}
},
{"Listing1":
{
"agency_code":"BPGA",
"property_code":"BONNSTG4-Lot11",
"Property_GUID":"6dded624-cde2-429a-81d4-bd6f91256345",
"FileNo /":"",
"country":"AUSTRALIA",
"state":"New South Wales",
"subregion /":""
}
}
]
}
我正在使用 $.ajax 来读取 JSON。文件加载成功。现在我如何访问各个“列表”以及如何测量总共存在多少个列表? 我尝试使用 $.each 循环遍历数组,但我的代码无法正常工作。
最佳答案
您有一个对象数组,但该数组不是第一层,它存储在顶级 Listings
属性中。
$.ajax({
dataType : 'json',
success : function (response) {
for (var i = 0, len = response.Listings.length; i < len; i++) {
//You can now access individual properties like this:
var agencyCode = response.Listings[i].Listing1.agency_code;
}
}
});
这个for
循环的执行速度比jQuery的.each()
或$.each()
:http://jsperf.com/jquery-each-vs-for-loops/2
这是一个演示:http://jsfiddle.net/btHy5/1/
关于jquery - 使用 jQuery 读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186453/