如何在Javascript中循环JSON对象?

时间:2017-03-13 10:45:23

标签: javascript php jquery json

我有以下JSON结构: -

Afghanistan
    : { latitude: "33.93911", longitude: "67.709953" }
American Samoa
    : { latitude: "-14.270972", longitude: "-170.132217" }
Australia
    : { latitude: "-25.274398", longitude: "133.775136" }

如何使用Javascript或Jquery循环播放它并获取所有,如澳大利亚,纬度,经度等?

我在PHP中使用 json_encode 函数创建了JSON格式。

以下是我正在创建JSON格式的原始Array格式: -

array (size=94)
  'India' => 
    array (size=2)
      'latitude' => string '20.593684' (length=9)
      'longitude' => string '78.96288' (length=8)
  'Pakistan' => 
    array (size=2)
      'latitude' => string '30.375321' (length=9)
      'longitude' => string '69.345116' (length=9)

2 个答案:

答案 0 :(得分:0)

使用引号和逗号修复JSON后使用以下JS代码:



var countries = {
  "Afghanistan": {
    "latitude": "33.93911",
    "longitude": "67.709953"
  },
  "American Samoa": {
    "latitude": "-14.270972",
    "longitude": "-170.132217"
  },
  "Australia": {
    "latitude": "-25.274398",
    "longitude": "133.775136"
  }
}
for (var country in countries) {
  values = countries[country];
  console.log('Country: ', country);
  console.log('Latitude: ', values.latitude);
  console.log('Longitude: ', values.longitude);
}




答案 1 :(得分:0)

假设您的var countries举行 AJAX 回复国家/地区 JSON。使用下面的代码来解决您的问题::

var countries = {
	"Afghanistan": {
		"latitude": "33.93911",
		"longitude": "67.709953"
	},
	"American Samoa": {
		"latitude": "-14.270972",
		"longitude": "-170.132217"
	},
	"Australia": {
		"latitude": "-25.274398",
		"longitude": "133.775136"
	}
}
$.each(countries, function (index, value) {
	console.log("Country=>" + index + ", Latitude=>" + value.latitude + ", Longitude=>" + value.longitude);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>