0

I have the following JSON structure: -

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

How do I loop through it using Javascript or Jquery and get all the values like Australia, latitude, longitude etc?

I am creating above JSON format from json_encode function in PHP.

Here is the original Array format from which I am creating JSON format: -

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)
SAMUEL
  • 8,098
  • 3
  • 42
  • 42
junaid afzal
  • 75
  • 1
  • 2
  • 10
  • 1
    use `.each()` to loop it – guradio Mar 13 '17 at 10:46
  • Possible duplicate of [looping over a json object array with jquery](http://stackoverflow.com/questions/6191646/looping-over-a-json-object-array-with-jquery) – kero Mar 13 '17 at 10:49
  • @guradio can you please elaborate more or give me any working example on how to use .each loop to get all values like country name, latitude, longitude etc. – junaid afzal Mar 13 '17 at 10:50

2 Answers2

0

Use the following JS code after fixing your JSON with quotes and commas:

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);
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Mircea Soaica
  • 2,829
  • 1
  • 14
  • 25
  • How I fix my JSON to use your code?? Because my values are dynamic and I am getting values through Ajax. Right I have more than 20 entries in my JSON. How I fixed that? – junaid afzal Mar 13 '17 at 10:57
  • You don't need to fix anything if you receive the JSON data from an AJAX call – Mircea Soaica Mar 13 '17 at 10:59
0

Assuming your var countries holding your AJAX response country JSON. Use below code to solve your problem::

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>
Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40