我下面有一个异步函数,它可以访问天气 API,我只想从 API 检索两条信息:F 和 C 中的温度。我删除了 API_Key,但可以在网站上免费获取一个,如果必要的。
由于我的 console.log(response) 语句,我可以确认我正在接收 json 对象,但我不确定如何以如此深度嵌入的 json 表示法访问这些数据点。
我想我的问题是,如果我想访问“完整”的完整城市名称,我想我会做类似response.observation_location.full的事情,但这不起作用......
帮忙?
async loadWeather() {
// let zip = this.args.zip || 97239;
let response = await fetch(`http://api.wunderground.com/api/API_KEY/conditions/q/CA/San_Francisco.json`);
console.log(response);
this.weather = await response.json();
// setTimeout( () => { this.loadWeather(); }, 2000);
}
这是响应 json 的部分输出:
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "San Francisco, CA",
"city": "San Francisco",
"state": "CA",
"state_name": "California",
"country": "US",
"country_iso3166": "US",
"zip": "94102",
"magic": "1",
"wmo": "99999",
"latitude": "37.77999878",
"longitude": "-122.41999817",
"elevation": "60.0"
},
"observation_location": {
"full": "SOMA, San Francisco, California",
"city": "SOMA, San Francisco",
"state": "California",
"country": "US",
"country_iso3166": "US",
"latitude": "37.778488",
"longitude": "-122.408005",
"elevation": "23 ft"
},
我尝试过执行 console.log(response["current_observation"])
只是为了访问嵌套数据值,但这似乎不起作用,因为它返回未定义。
最佳答案
好吧,我解决了自己的问题,但为了记录:
响应需要通过 resonse.json() 转换为 json
然后我就可以按预期访问属性
this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);
关于javascript - 从 wunderground API 访问 json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44915502/