2016-03-05 49 views
0

我有困難的時間遍歷這個數據集從ajax調用拉到天氣api。我想獲取諸如temp或id之類的東西的值,但不斷收到錯誤。我試過這個weather.weather ['id'],weather.weather.id,weather.weather [0]。我知道最高的天氣層是一個物體。但第二個天氣傳遞數組?那有一個對象?我如何從這裏獲取信息?對於正常的數據集我有一些想法,但這對我來說太奇怪了。注:這是VUEJSAjax數據對象意外行爲

AJAX調用:

$.getJSON('http://api.openweathermap.org/data/2.5/weather?id=6356055&appid=44db6a862fba0b067b1930da0d769e98', function(weather) { 
       this.weather_data = weather; 
      }.bind(this)); 

這是穿我的數據推到我的空數組

weather_data: [], 

那麼現在我只是在努力確保其內的一些工作這樣的標籤:

{{ weather_data.weather[0].id | json}} 

這裏是從getjson調用中拉回來的東西。

 "weather": { 
     "coord": { 
      "lon": 2.13, 
      "lat": 41.4 
     }, 
     "weather": [ 
      { 
       "id": 800, 
       "main": "Clear", 
       "description": "clear sky", 
       "icon": "01d" 
      } 
     ], 
     "base": "cmc stations", 
     "main": { 
      "temp": 285.622, 
      "pressure": 1006.71, 
      "humidity": 98, 
      "temp_min": 285.622, 
      "temp_max": 285.622, 
      "sea_level": 1015.25, 
      "grnd_level": 1006.71 
     }, 
     "wind": { 
      "speed": 2.61, 
      "deg": 267.501 
     }, 
     "clouds": { 
      "all": 0 
     }, 
     "dt": 1457178093, 
     "sys": { 
      "message": 0.0042, 
      "country": "ES", 
      "sunrise": 1457158704, 
      "sunset": 1457200063 
     }, 
     "id": 6356055, 
     "name": "Barcelona", 
     "cod": 200 
    }, 

嘗試這種weather_data.weather yeilds這個

  [ 
    { 
    "id": 801, 
    "main": "Clouds", 
    "description": "few clouds", 
    "icon": "02d" 
    } 
] 
+0

https://jsfiddle.net/mca27kfr/ – Rayon

+0

data.weather.weather [0] .id將提供結果。向我們展示如何解析和訪問數據。 – Aravind

+0

我添加了更多詳細信息 –

回答

0

首先,這種類型的問題我建議你使用的console.log(your_variable),並期待在瀏覽器的控制檯(在Chrome F12)你真的有什麼。否則,如果您的原始api響應存儲在名爲「data」的變量中,data.weather.weather [0] .id應該可以工作。

+0

檢查編輯。我添加了更多的細節。我認爲這也會起作用,但vuejs的行爲很怪異 –

+0

@RickiMoore,你將weather_data定義爲數組。但是從你的API你會得到一個對象。可能你想要做的是:this.weather_data = weather.weather。然後稍後,您會執行this.weather_data [0] .id以獲取該ID。 – amberv

+0

我試過了,它給了我calendar_component.js:1385Uncaught TypeError:無法讀取屬性'id'的undefined –