如何从 OpenWeatherMap 获取天气描述 API
How to get the weather description from OpenWeatherMap API
我正在尝试从 OpenWeatherMap
API 获取法语天气描述,但我卡住了。
请问我做错了什么?
var urlBase = "http://api.openweathermap.org/data/2.5/weather?id=";
var apiKey = "&appid=xxx";
var unitsParam = "&units=metric";
var language = "&lang=fr";
var url = urlBase + cityCode + unitsParam + language + apiKey ;
startWebRequest (url, function(status, type, content) {
var data = JSON.parse(content);
console.log(data);
setScreen('screen2');
setText("label1",data.name);
setText('label2',data.main.temp);
setText('label3',data.main.feels_like);
setText('label4',data.weather.description[0]);
我收到 undefined
错误,我卡住了。
TypeError: data.weather.description is undefined.
你能看看我的代码并帮助我吗?
根据 API 文档,description
是 string
,而不是 array
。但你的天气键也是 array
.
因此,要按照您的预期正确访问 description
,您需要这样做:
data.weather[0].description
不是:
data.weather.description[0]
但请注意,如果 weather
数组为空,您可能会遇到问题。
按照我上面的建议进行操作将解决您遇到的 TypeError
。
如果您遇到 setText
值为 undefined
的问题。只需使用空字符串作为后备。
像这样:
setText('label4', data.weather[0] ? data.weather[0].description : '')
根据返回的对象,您应该以这种方式访问描述:data.weather[0].description
我正在尝试从 OpenWeatherMap
API 获取法语天气描述,但我卡住了。
请问我做错了什么?
var urlBase = "http://api.openweathermap.org/data/2.5/weather?id=";
var apiKey = "&appid=xxx";
var unitsParam = "&units=metric";
var language = "&lang=fr";
var url = urlBase + cityCode + unitsParam + language + apiKey ;
startWebRequest (url, function(status, type, content) {
var data = JSON.parse(content);
console.log(data);
setScreen('screen2');
setText("label1",data.name);
setText('label2',data.main.temp);
setText('label3',data.main.feels_like);
setText('label4',data.weather.description[0]);
我收到 undefined
错误,我卡住了。
TypeError: data.weather.description is undefined.
你能看看我的代码并帮助我吗?
根据 API 文档,description
是 string
,而不是 array
。但你的天气键也是 array
.
因此,要按照您的预期正确访问 description
,您需要这样做:
data.weather[0].description
不是:
data.weather.description[0]
但请注意,如果 weather
数组为空,您可能会遇到问题。
按照我上面的建议进行操作将解决您遇到的 TypeError
。
如果您遇到 setText
值为 undefined
的问题。只需使用空字符串作为后备。
像这样:
setText('label4', data.weather[0] ? data.weather[0].description : '')
根据返回的对象,您应该以这种方式访问描述:data.weather[0].description