【问题标题】:Looping through JSON response objects循环访问 JSON 响应对象
【发布时间】:2018-06-29 01:45:52
【问题描述】:

拜托,我想循环访问来自 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)
        }

    
    }
    
}

请问我做错了什么

【问题讨论】:

  • 看起来内循环应该是 for(x in json.results[key])...
  • 我的解决方案不起作用吗?!

标签: javascript json pwa


【解决方案1】:

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

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

    }

}

【讨论】:

  • @OgbonnaVitalis NP!
  • nice.... async/await 也可以这样使用!!!我认为必须使用then
  • @AmitKumar 我对async-await 一无所知,但我想脚本不能对json 做任何事情,直到两个带有await 关键字的语句都得到解决
【解决方案2】:

将您的 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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 2019-02-11
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多