I'am trying to display json
data with a loop.
I am getting the following results but don't know how to display them with loop.
[
{"latitude":"23.046100780353495","longitude":"72.56860542227514"},
{"latitude":"23.088427701737665","longitude":"72.49273109366186"},
{"latitude":"23.061264193197644","longitude":"72.68224525381811"},
{"latitude":"22.977212139977677","longitude":"72.52191352774389"},
{"latitude":"23.002180435752084","longitude":"72.47590827872045"},
{"latitude":"23.108638843843046","longitude":"72.49444770743139"}
]
I have created this loop:
var obj = JSON.parse(data);
var total = obj.length;
for (var i = 0; i < total; i++) {
console.log([i]);
}
and tried to display the results like this:
23.046100780353495,72.56860542227514
23.088427701737665,72.49273109366186
23.061264193197644,72.68224525381811
22.977212139977677,72.52191352774389
23.002180435752084,72.47590827872045
23.108638843843046,72.49444770743139
Some tips:
{}
parentheses are objects , you access properties like object.property
. []
parentheses are arrays , you access elements by indexes array[index]
. In your particular case, this should do it:
var objects_array = JSON.parse(data); // This is an array of objects.
var total = objects_array.length;
for (var i = 0; i < total; i++) {
var obj = objects_array[i]; // This is one object from the array.
console.log( obj.latitude + ',' + obj.longitude ); // We access object properties using a dot.
}
Your array already has default keys. So try something in the manner of:
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value) {
console.log(value.latitude, value.longitude);
});
var obj = JSON.parse(data);
var total = obj.length;
for (var i = 0; i < total; i++) {
console.log(obj[i].latitude + ', ' + obj[i].longitude);
}
JSON values can be accessed using the .dot
notation.
Here you have named an array of objects as obj
. I would recommend renaming obj
to a more descriptive name such as coordinates
or coordinatesArray
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.