sterg sterg - 3 months ago 24
Javascript Question

Weather API and JSON

So,I am trying to use the Open Weather API: http://openweathermap.org/current


Here is my javascript code:

$(document).ready(function() {



if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$(".ok").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
var ur="http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&appid=18c7e2b6b0150a8f1d2c6b946e065697";
$.getJSON(ur, function(json) {
$(".ok2").html(JSON.stringify(json));


alert(json.weather[main]);

});

});
}
});


Here is the expected output:

{"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200}




The output is displayed correctly in my test page but the alert(json.weather[main]); doesn't work and I want to know how can I access the particular keys of my JSON Object.For example if I want to access the id shouldn't the following do it for me: json.id; ?

Answer

json.weather is an array:

json.weather = [{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}]

An array is a container object that holds a number of values of a multiple types in Javascript, to access these values you must specified Integer index.

json.weather[0] = {"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}

json.weather[0] is an Javascript Object and you must specify the property name, you can access the properties in two ways:

  • jsonObject["propertyName"]
  • jsonObject.propertyName

So

Just change this:

alert(json.weather[main]);

With:

alert(json.weather[0].main);