Weather API and JSON

Weather API and JSON

本文关键字:JSON and API Weather      更新时间:2023-09-26

所以,我试图使用开放天气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对象的特定键。例如,如果我想访问id,下面不应该为我做:div ?

json。是一个数组:

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

数组是一个容器对象,在Javascript中保存多个类型的值,要访问这些值必须指定Integer index。

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

json。weather[0]是一个Javascript对象,你必须指定属性名,您可以通过两种方式访问这些属性:

  • jsonObject [propertyName"]
  • jsonObject.propertyName
<标题>所以h1> 改一下:
alert(json.weather[main]);

:

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

在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)不是固定的,例如依赖于变量等时,使用括号