我正在使用 Openweathe map 的每小时天气预报 API 调用来构建天气应用程序。我可以正确获取调用的 URL,但显示的 JSON 结构似乎与作为示例提供的结构不匹配。我无法访问 data.list
或 data.sys
或 data.city.name
。虽然我可以访问data.name
。
这是示例 JSON
{
cod: "200",
message: 0.0208,
cnt: 96,
list: [
{
dt: 1553709600,
main: {
temp: 286.44,
temp_min: 286.258,
temp_max: 286.44,
pressure: 1015.82,
sea_level: 1015.82,
grnd_level: 1002.193,
humidity: 100,
temp_kf: 0.18
},
weather: [
{
id: 500,
main: "Rain",
description: "light rain",
icon: "10d"
}
],
clouds: {
all: 86
},
wind: {
speed: 5.51,
deg: 202.816
},
rain: {
1h: 0.812
},
sys: {
pod: "d"
},
dt_txt: "2019-03-27 18:00:00"
},
...
],
city: {
id: 420006353,
name: "Mountain View",
coord: {
lat: 37.3894,
lon: -122.0833
},
country: "US"
}
}
这是我用来管理通话的代码
function call(city,country,zip) {
let countryCode = list.getCode(country);
let API;
if (city!="" && country!="") {
API = 'http://api.openweathermap.org/data/2.5/weather?q='+city.toLowerCase()+','+countryCode.toLowerCase()+'&APPID=1a9b84b61d1a8d6fdbb52fa2800ef894';
}
else if(country!="" && zip!=""){
API ='http://api.openweathermap.org/data/2.5/forecast/hourly?zip='+zip.toString()+','+countryCode.toLowerCase()+'&APPID=1a9b84b61d1a8d6fdbb52fa2800ef894';
}
else{
alert("Please type your city or Zip code");
}
return API;
}
function getPlace() {
let city = cityInput.value;
let country = countryInput.value;
let zip = zipInput.value;
let APICall=call(city,country,zip);
fetch(APICall).then(response=>{
return response.json();
}).then(data=>{
let cityName= data.name;
settler(cityName);
})
}
我应该能够访问data.list
但是
alert(data.list.lenght)
给我一个错误,指出无法定义未定义的长度。与 alert(data.city.name)
相同,表示无法访问未定义的 name 属性。
最佳答案
weather
API 文档正确显示了您期望的 weather
查询数据:
https://openweathermap.org/current
如果您到达正确的端点 (pro
),而您的(公开的;您应该修复该问题)API key 对其无效 (AFAICT),则您的每小时
查询应该可以工作.
pricing page表示每小时
数据不是免费提供的。
关于javascript - Openweathermap API 调用响应错误的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157886/