0

拜托,我想循环访问来自 API 的这个 json 响应,当我将它记录到控制台时,我一直不确定。

   {
              "results": {
                  "AF": {
                      "alpha3": "AFG",
                      "currencyId": "AFN",
                      "currencyName": "Afghan afghani",
                      "currencySymbol": "؋",
                      "id": "AF",
                      "name": "Afghanistan"
                  },
                  "AI": {
                      "alpha3": "AIA",
                      "currencyId": "XCD",
                      "currencyName": "East Caribbean dollar",
                      "currencySymbol": "$",
                      "id": "AI",
                      "name": "Anguilla"
                  },
                  "AU": {
                      "alpha3": "AUS",
                      "currencyId": "AUD",
                      "currencyName": "Australian dollar",
                      "currencySymbol": "$",
                      "id": "AU",
                      "name": "Australia"
                  }
                }
            }

这是我的代码:

async function currency() {
    const response = await fetch(`https://free.currencyconverterapi.com/api/v5/currencies`);
    const json = await response.json();
    //console.log(json.results);
    for (key in json.results) {
    
        for(x in key){
            console.log(x)
        }

    
    }
    
}

请问我做错了什么

4

3 回答 3

2

我相信下面的小修改应该足够了......让我知道它是否有效。

async function currency() {
    const response = await fetch(`https://free.currencyconverterapi.com/api/v5/currencies`);
    const json = await response.json();
    //console.log(json.results);
    for (key in json.results) {

       for(x in json.results[key]){
           console.log(json.results[key][x])
       }

    }

}
于 2018-06-28T17:34:52.903 回答
0

将您的 json obj 转换为 Map Object 或 Set Object 。然后你可以尝试循环它

var myMap = new Map(); myMap.set(jsonResp);

for (let data of myMap.keys()) { console.log(data); }

在这里查看更多信息

和。 更多细节在这里

于 2018-06-28T17:35:09.133 回答
0

我不是 async/await 的常用用户,但我认为正确的方法是,

async function currency() {
    const response = await fetch(`https://free.currencyconverterapi.com/api/v5/currencies`);
    const json = await response.json();  
    return json;      
}
currency().then(data=>{
    console.log(data);
});
于 2018-06-28T17:45:52.590 回答