请,我想通过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)
}
}
}
请问我在做什么错
答案 0 :(得分: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])
}
}
}
答案 1 :(得分:0)
将您的json obj转换为Map Object或Set Object。然后您可以尝试遍历
var myMap = new Map(); myMap.set(jsonResp);
用于(让myMap.keys()的数据){console.log(data); }
答案 2 :(得分:0)
我不是异步/等待的经常用户,但我认为正确的方法是
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);
});