我在下面有一个异步函数,可以连接到一个天气API,我只想从API中检索两条信息:华氏温度。我删除了API_Key,但如果需要的话,可以在网站上免费获取一个。
由于我的console.log(response)语句,我可以确认我正在接收json对象,但我不确定如何在这种高度嵌入的json表示法中访问这些数据点。
我想我的问题是,如果我想访问城市全名,说' full‘,我想我会做一些类似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"]),但这似乎不起作用,因为它返回未定义的值。
发布于 2017-07-05 18:42:45
好吧,我解决了我自己的问题,但需要说明的是:
响应需要通过resonse.json()转换为json
然后我就可以像预期的那样访问属性
this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);https://stackoverflow.com/questions/44915502
复制相似问题