【问题标题】:Accessing json data from wunderground API?从 wunderground API 访问 json 数据?
【发布时间】:2017-12-08 11:44:28
【问题描述】:

我在下面有这个异步函数,它接入天气 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"]) 只是为了访问嵌套数据值,但这似乎不起作用,因为它返回未定义。

【问题讨论】:

标签: javascript json api


【解决方案1】:

好的,我解决了我自己的问题,但记录在案:

response 需要通过 resonse.json() 转换为 json

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多