如何用JavaScript从JSON响应中提取result字段数据?
解决方法
你当前的问题是用res.text()把API响应转换成了字符串格式,所以无法直接访问result属性。要获取这个值,你需要把响应解析成JavaScript对象,有两种简单的方式:
方法一:使用res.json()(推荐)
fetch提供了res.json()方法,可以直接将JSON格式的响应体解析为对象,这样就能直接通过点语法访问result:
const currency_one = currencyOne.value; const currency_two = currencyTwo.value; const myHeaders = new Headers(); myHeaders.append('apikey', API_KEY); const requestOptions = { method: 'GET', redirect: 'follow', headers: myHeaders, }; fetch( `https://api.apilayer.com/exchangerates_data/convert?to=${currency_one}&from=${currency_two}&amount=${amountOne.value}`, requestOptions ) .then((res) => res.json()) // 替换res.text()为res.json() .then((data) => console.log(data.result)) // 直接访问result属性 .catch((err) => console.log('error', err));
方法二:手动解析字符串
如果你坚持使用res.text(),可以用JSON.parse()把字符串转换成对象后再取值:
const currency_one = currencyOne.value; const currency_two = currencyTwo.value; const myHeaders = new Headers(); myHeaders.append('apikey', API_KEY); const requestOptions = { method: 'GET', redirect: 'follow', headers: myHeaders, }; fetch( `https://api.apilayer.com/exchangerates_data/convert?to=${currency_one}&from=${currency_two}&amount=${amountOne.value}`, requestOptions ) .then((res) => res.text()) .then((data) => { const jsonData = JSON.parse(data); // 将字符串解析为JSON对象 console.log(jsonData.result); }) .catch((err) => console.log('error', err));
内容的提问来源于stack exchange,提问作者banaya
相关产品推荐
相关产品推荐

