2016-12-30 149 views
0

新手在這裏,我試圖從FreeCodeCamp的項目訪問OpenWeatherMap API的溫度。但我的問題是,每當我嘗試使用嵌套的JSON對象訪問溫度值時,控制檯建議「temp」的父級未定義。爲什麼沒有定義?OpenWeatherMap API:未捕獲TypeError - 無法讀取未定義屬性'temp'(...)

這是給我的問題代碼:

$.getJSON(url, function(data) { 
    console.log("successful request"); 
    console.log(data.main.temp); 
    console.log("successful temperature access"); 
    }); 

當我運行此,控制檯日誌「請求成功」,然後給我的錯誤:

Uncaught TypeError - Cannot read property 'temp' of undefined(...).

事情我必須嘗試過:我查看了示例代碼並參考了API文檔,並且看到data.main.temp是訪問溫度的有效方法。我驗證了data對象已被解析並確保它不包含在數組中。另外,我已驗證了網址。這是什麼樣的URL導致一個開始片段: link.

工作過的Chrome。 Link到Codepen項目。

+0

請編輯您的問題,以包含[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – MJH

回答

1

天氣數據以字符串形式返回。你需要把它解析成JSON這樣的:

$.getJSON(url, function(data) { 
    var weatherData = JSON.parse(data.content); 
    console.log("successful request"); 
    console.log(weatherData.main.temp); 
    console.log("successful temperature access"); 
}); 
0

想通了!我下載了一個Chrome擴展JSON格式器,它讓我看到主要實際上是list下的一個元素。正確的電話是data.list[0].main.temp

相關問題