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

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

问题描述:

我想从wunderground获取天气预报和条件,但是当我运行代码时,current_observation发生错误,api的边数据json中的current_observation。未捕获TypeError:无法读取未定义的属性'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); 
     } 
    } 
}); }); 
+0

'for(index in forecast,conditions){'Whyt is',conditions' there?这使得它忽略'forecast'并使用'conditions',这在你的例子中没有定义。 – 2015-09-05 16:43:37

+0

在json数据中我们有太多的对象,预测和条件 – aligassan

+0

@aligassan这不是JSON的工作方式。顶层包含'response','current_observation'和'forecast'键。你不能一次循环两件事;这个不成立。 –

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

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

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

+0

你能给我完整答案 – aligassan

+2

@aligassan我做过;我告诉过你如何得到目前的观察结果。这不是一个真正的“为我做所有我的工作”的地方,这更像是“教一个人钓鱼”的地方,至少对我来说。看看JSON - 我就是这么做的。 –

其因为parsed_json['forecast']['txt_forecast']['forecastday']没有conditions在里面。所以parsed_json['forecast']['txt_forecast']['forecastday']['conditions']将是未定义的,你要求在undefined之上的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" 
    }] 
    } 
}