简体   繁体   English

如何使用json数据进行循环?

[英]How to make the loop with json data?

I'am trying to display json data with a loop. 我正在尝试使用循环显示json数据。

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 . {}括号是对象 ,您可以访问诸如object.property类的object.property
  • [] parentheses are arrays , you access elements by indexes array[index] . []括号是数组 ,您可以通过索引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. 可以使用.dot表示法访问JSON值。

Here you have named an array of objects as obj . 在这里,您已将对象数组命名为obj I would recommend renaming obj to a more descriptive name such as coordinates or coordinatesArray . 我建议将obj重命名为更具描述性的名称,例如coordinatescoordinatesArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM