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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With