未捕获的TypeError:无法读取未定义的属性“current_observation”

时间:2015-09-05 16:40:55

标签: javascript api

我想从wunderground获取天气预报和条件,但是当我运行代码时出现current_observation错误,api的side数据json中的current_observation。

$(document).ready(function($){
$.ajax({
    url: "http://api.wunderground.com/api/72df18b7f213607b/conditions/forecast/lang:AR/q/CO/zmw:00000.1.WKQTZ.json",
    dataType : "jsonp",
    success : function(parsed_json) {
        var forecast = parsed_json['forecast']['txt_forecast']['forecastday']['conditions']['current_observation'];

        for (index in forecast,conditions) {
            var newForecastString = 'Weather forecast for ' + forecast[index]['title'] + ' is ' + forecast[index]['fcttext_metric'];
        var newconditionsString = 'Weather forecast for ' + forecast[index]['title'] + ' is ' + forecast[index]['station_id'];
            var newForecastParagraph = $('<p/>').text(newForecastString);
            $("body").append(newForecastParagraph);
        } 
    }
}); }); 

2 个答案:

答案 0 :(得分:0)

current_observation位于顶层,例如parsed_json['current_observation]。

不相关,但发布JSON可能比公开API密钥更好。

如果你正在寻找条件,它们不是任何地方的数组,它们是一个单独的字符串值,可以在各个地方找到。

答案 1 :(得分:0)

因为parsed_json['forecast']['txt_forecast']['forecastday']中没有conditions。因此parsed_json['forecast']['txt_forecast']['forecastday']['conditions']将是未定义的,您要求current_observation在未定义的基础上。

 "forecast":{
   "txt_forecast": {
    "date":"6:28 PM AST",
    "forecastday": [{
    "period":0,
    "icon":"clear",
    "icon_url":"http://icons.wxug.com/i/c/k/clear.gif",
    "title":"السبت",
    "fcttext":"صافٍ غالبًا. درجة الحرارة الصغرى 81 درجة فهرنهيت.",
    "fcttext_metric":"صافٍ غالبًا. درجة الحرارة الصغرى 27 درجة مئوية.",
    "pop":"0"
    }]
   }
}