Reputation: 1
I am trying to access data from a JSON file hosted on the web. The JSON is formated as follows:
{"markers":[
{
"latitude":57.7973333,
"longitude":12.0502107,
"title":"Angered",
"content":"Representing :)"
},
{
"latitude":57.6969943,
"longitude":11.9865,
"title":"Gothenburg",
"content":"Swedens second largest city"
}
]
"markersupdate": []
}
My goal is to get the data from the objects, such as latitude and longitude. I tried the following code:
$.ajax({
type: "GET",
url: 'URL TO MY JSON',
dataType: "json",
success: function (data) {
if (data.length !== 0) {
//Here I tried using data.markers istead of data, but it did not seem to work
$.each( data, function (marker, data) {
//Here I want to be able to access e.g. data.longitude
});
}
},
});
The problem seems to be that it doesn't import the data correctly.
How do I solve this?
Thanks
Upvotes: 0
Views: 90
Reputation: 1038720
Make sure that you are iterating over the markers
property which is the array. So adjust your if
condition as well as the object you are iterating over:
success: function (data) {
if (data.markers.length !== 0) {
$.each(data.markers, function (index, marker) {
alert(marker.longitude);
});
}
}
Also notice that the first parameter of the callback passed to the $.each
function is the index of the element in the array and the second parameter is the element itself. Alternatively you could use this
to access the current element that is being iterated upon:
$.each(data.markers, function () {
alert(this.longitude);
});
Upvotes: 1