I have a JSON file and i have to read data from this file when the page loads. I suspect there is something wrong with my JSON Structure. JSONLint is showing that it is valid. So i must be using the wrong method to access it.
It is basically an array of objects (or that is what i think).
{"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 /":""
}
}
]
}
I am using the $.ajax to read the JSON. The file is loading successfully. Now how do i access the individual "listings" and how to measure how many Listings are present in total? I tried the $.each to loop through the array but my code is not working.
1 Answer 1
You have an array of objects, but that array is not the first tier, it's stored in the top-level Listings property.
$.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;
}
}
});
This for loop will perform faster than jQuery's .each() or $.each(): http://jsperf.com/jquery-each-vs-for-loops/2
Here is a demo: http://jsfiddle.net/btHy5/1/
7 Comments
len = response.Listings.length in the for loop. In your code you don't really need to get the total number of rows since you are using $.each().$(function() { $.ajax({ type: 'GET', datatype: 'JSON', url: 'scripts/Listing.json', success: processJSON }); function processJSON(data) { $.each(data.Listings,function(i,item) { console.log(data.Listings.length); }); } }); It is giving me different errors in different browser. Chrome is showing that it cant find length property for undefined.console.log(data), then a console.log(data.Listings);. Work from what you know to be true toward the error you are trying to get rid of.
Listings, that contains the array of objects you probably want to iterate over. It's impossible to tell unless you show the code that does this.