遍历 JSON 个响应对象

Looping through JSON response objects

拜托,我想遍历来自 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)
        }

    
    }
    
}

请问我做错了什么

我相信下面的小修改应该足够了...如果有效请告诉我。

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])
       }

    }

}

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

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

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

Check here for more information

还有。 More details here

我不是 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);
});