Weather API和JSON

时间:2016-08-21 21:43:56

标签: javascript json

所以,我正在尝试使用Open Weather API:http://openweathermap.org/current

这是我的javascript代码:

$(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]);

        });

  });
}
});

这是预期的输出:

{"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}


输出在我的测试页面中正确显示但警报(json.weather [main]);不起作用,我想知道如何访问我的JSON Object的特定键。例如,如果我想访问id,不应该为我做以下操作:json.id; ?

2 个答案:

答案 0 :(得分:2)

json.weather 是一个数组:

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

数组是一个容器对象,它在 Javascript 中包含多个类型的多个值,以访问必须指定的值 Integer 索引。

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

json.weather [0] Javascript对象 ,您必须指定属性名称, 您可以通过两种方式访问​​属性:

  • jsonObject [“propertyName”]
  • jsonObject.propertyName

所以

只需改变一下:

alert(json.weather[main]);

使用:

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

答案 1 :(得分:0)

您可以通过两种方式在JavaScript中访问对象的属性。首先,使用点符号:

object.property // after the dot, literally write the name of the property

和第二,使用括号:

object["property"] // in the [], put any expression

括号采用任何表达式,并使用该表达式的值作为要访问的属性的名称。因此,首先编写weather[main]来计算括号中的表达式:main。这是一个变量名,因此它将计算main变量的值(或者,如果main不存在,则会抛出错误。)

如果要访问具有固定名称的属性,通常应使用点符号。因此alert(json.weather[main]);应为alert(json.weather.main);简单。

当要访问的属性的名称(a)不是有效的标识符时,使用括号,例如,包含特殊字符,或(b)不固定,例如取决于变量等。