从wunderground API访问json数据?

时间:2017-07-05 00:27:38

标签: javascript json api

我在下面有这个异步功能,可以使用天气API,我只想从API中检索两条信息:F& C.我删除了API_Key,但如果有必要,可以在网站上免费获取。

由于我的console.log(响应)语句,我可以确认我收到了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"]),但这似乎不起作用,因为它返回undefined。

1 个答案:

答案 0 :(得分:1)

好的,我解决了自己的问题,但是为了记录:

响应需要通过resonse.json()

转换为json

然后我可以按预期访问属性

this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);