简体   繁体   English

难以访问 api 返回的 json 数组中的信息。 我究竟做错了什么?

[英]Difficulty accessing information in api's returned json array. What am I doing wrong?

I am trying to get information out of a json response from the weather.gov api ( https://api.weather.gov/ ).我正在尝试从 weather.gov api( https://api.weather.gov/ )的 json 响应中获取信息。 There's a good chance that I'm overthinking my problem, because I am getting the expected number of responses, but all 2,748 of those responses are 'undefined'.我很有可能过度思考了我的问题,因为我得到了预期的回复数量,但所有 2,748 个回复都是“未定义的”。

I've tried accessing the properties that I have seen in the json object response via dot notation, I have tried.map and.forEach methods to possibly try to get a different output, and I have read several dozen blog posts that seem to deal with "simpler" api's. I've tried accessing the properties that I have seen in the json object response via dot notation, I have tried.map and.forEach methods to possibly try to get a different output, and I have read several dozen blog posts that seem to deal使用“更简单”的 api。 I have also read several posts here on SO, but I have not been able to understand what's wrong.我也在这里阅读了几篇关于 SO 的帖子,但我无法理解出了什么问题。

I'm pretty sure at this point that my mistake is small, but I can't see it.在这一点上,我很确定我的错误很小,但我看不到。


const endpoint = 'https://api.weather.gov/stations/';

async function getStations() {
    const response = await fetch(endpoint);
    const data = await response.json();

    stationInfo = data.observationStations;
    // data.observationStations.forEach(function(e) {
    //     console.log(e.properties);
    // });

    for(let i in stationInfo) {
        // ext = stationInfo[i].slice(-4);
        // console.log(endpoint + ext);
        console.log(stationInfo[i].id)
    }
}

getStations();

here is an example of the json that I'm trying to work with这是我正在尝试使用的 json 的示例

{
    "@context": [
        "https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
        {
            "wx": "https://api.weather.gov/ontology#",
            "s": "https://schema.org/",
            "geo": "http://www.opengis.net/ont/geosparql#",
            "unit": "http://codes.wmo.int/common/unit/",
            "@vocab": "https://api.weather.gov/ontology#",
            "geometry": {
                "@id": "s:GeoCoordinates",
                "@type": "geo:wktLiteral"
            },
            "city": "s:addressLocality",
            "state": "s:addressRegion",
            "distance": {
                "@id": "s:Distance",
                "@type": "s:QuantitativeValue"
            },
            "bearing": {
                "@type": "s:QuantitativeValue"
            },
            "value": {
                "@id": "s:value"
            },
            "unitCode": {
                "@id": "s:unitCode",
                "@type": "@id"
            },
            "forecastOffice": {
                "@type": "@id"
            },
            "forecastGridData": {
                "@type": "@id"
            },
            "publicZone": {
                "@type": "@id"
            },
            "county": {
                "@type": "@id"
            }
        }
    ],
    "id": "https://api.weather.gov/stations/KVBS",
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [
            -93.629999999999995,
            29.48
        ]
    },
    "properties": {
        "@id": "https://api.weather.gov/stations/KVBS",
        "@type": "wx:ObservationStation",
        "elevation": {
            "value": 68.275199999999998,
            "unitCode": "unit:m"
        },
        "stationIdentifier": "KVBS",
        "name": "SABINE 13B OIL PLATFORM",
        "timeZone": "America/Chicago",
        "forecast": "https://api.weather.gov/zones/forecast/GMZ450"
    }
}

Since I was successful in getting the url's for each item in the json array, I expected to be able to access the properties of those items also - instead, I'm getting 'undefined'.由于我成功获取了 json 数组中每个项目的 url,我希望也能够访问这些项目的属性 - 相反,我得到了“未定义”。 However as I said earlier, I'm getting 'undefined' the expected number of times.然而,正如我之前所说,我得到“未定义”的预期次数。

Hi you could try something like:您好,您可以尝试以下方法:

 const endpoint = 'https://api.weather.gov/stations/'; const getStations = async () => { const response = await fetch(endpoint); const data = await response.json(); data.observationStations.forEach(item => console.log(item)); } getStations();

Looping the observationStations you just need a simple forEach循环观察站你只需要一个简单的 forEach

 const endpoint = 'https://api.weather.gov/stations/'; const getStations = async () => { const response = await fetch(endpoint); const data = await response.json(); data.observationStations.forEach(station => console.log(station) ) } getStations();

HOWEVER You likely want to access the features object array:但是,您可能希望访问 object 数组的功能:

 const endpoint = 'https://api.weather.gov/stations/'; const getStations = async() => { const response = await fetch(endpoint); const data = await response.json(); const list = data.features.map(feat => `<dt>${feat.properties.stationIdentifier}</dt> <dd><a href="${feat.id}">${feat.properties.name}</a></dd>` ) document.getElementById('list').innerHTML = list.join(''); } getStations();
 a { text-decoration: none } dl { border: 3px double #ccc; padding: 0.5em; } dt { float: left; clear: left; width: 70px; /* text-align: right; */ font-family: monospace; font-size: 16px; white-space: pre; font-weight: bold; color: green; } dt::after { content: ":"; } dd { margin: 0 0 0 50px; padding: 0 0 0.1em 0; }
 <dl id="list"></dl>

the point is that observationStations attribute object obtained from https://api.weather.gov/stations/ is an array of strings not objects.关键是从https://api.weather.gov/stations/获得的observationStations属性 object 是一个字符串数组而不是对象。

Therefore to print the string you should do:因此,要打印字符串,您应该这样做:

console.log(stationInfo[i])

instead of:代替:

console.log(stationInfo[i].id)

Hope it helps希望能帮助到你

If you want to access observationStations :如果您想访问observationStations

 const endpoint = 'https://api.weather.gov/stations/'; async function getStations() { console.log('calling'); const data = await fetch(endpoint).then(res => res.json()); const observationStations = data.observationStations; observationStations.forEach(observationStation => console.log(observationStation)); } getStations();

But just an NB I don't think you should make this kind of calls ( retrieving all the stations at once).但只是一个 NB,我认为您不应该拨打这种电话(一次检索所有电台)。 Maybe there is a much better call which takes much less time from the API.也许有一个更好的调用,它从 API 花费的时间要少得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM