簡體   English   中英

jQuery getJSON從API如何訪問對象?

[英]jQuery getJSON from API how to access object?

我正在嘗試從API獲取JSON,然后訪問JSON的"weather"對象的"main"對象。

當我使用此代碼時:

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
  var data = JSON.stringify(json);
  alert(data);
});

我得到以下輸出:

{
  "coord": {
    "lon": 159,
    "lat": 35
  },
  "weather": [{
    "id": 500,
    "main": "Rain",
    "description": "light rain",
    "icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F10n.png?1499366021399"
  }],
  "base": "stations",
  "main": {
    "temp": 22.59,
    "pressure": 1027.45,
    "humidity": 100,
    "temp_min": 22.59,
    "temp_max": 22.59,
    "sea_level": 1027.47,
    "grnd_level": 1027.45
  },
  "wind": {
    "speed": 8.12,
    "deg": 246.503
  },
  "rain": {
    "3h": 0.45
  },
  "clouds": {
    "all": 92
  },
  "dt": 1499521932,
  "sys": {
    "message": 0.0034,
    "sunrise": 1499451436,
    "sunset": 1499503246
  },
  "id": 0,
  "name": "",
  "cod": 200
}

現在,我要獲取的輸出是"Rain""weather"對象的"main"對象的屬性(希望我說的沒錯,我是初學者))。

從邏輯上講,我會這樣做:

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
  var data = JSON.stringify(json);
  alert(data["weather"].main);
});

但這並沒有給我任何輸出。

我做了一些搜索,發現我應該解析。

但是當我這樣做時:

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
  var data = JSON.stringify(json);
  var Jason = JSON.parse(data);
  alert(Jason["weather"].main);
});

我又沒有undefined為我的輸出。

那么,我的代碼應該是什么樣子,所以我的輸出將是"Rain"

PS:對不起,如果我在描述問題時犯了錯誤,我真的是JavaScript / jQuery的新手,英語也是我的第二語言。

您幾乎擁有了它,只需訪問天氣后再添加[0]即可。 由於weather是一個Array,因此需要使用它來獲取第一個元素的數據:

 $.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", json => console.log(json.weather[0].main) ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

另外, getJSON函數已經為您解析了JSON,不需要其他JSON.parse

JSON.Stringify將json轉換為字符串。 如果要訪問對象,則需要JSON對象而不是字符串。

天氣是一個對象數組,您需要使用索引訪問數組。 您需要第一個對象時,請使用json["weather"][0]

$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json){
  alert(json["weather"][0].main);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM