<!DOCTYPE html>
<html lang="en">
<body>
<h1>show me btc current rate</h1>
<p>
current btc rate: <span id="btc_rate"></span><br />
</p>
<script>
const api_url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json';
async function getBTC()
{
const response = await fetch(api_url);
const data = await response.json();
const {rate} = data;
document.getElementById('btc_rate').textContent = rate;
}
getBTC();
</script>
</body>
</html>
我试图从https://api.coindesk.com/v1/bpi/currentprice/BTC.json中获取比特币的当前汇率,但不知怎么的,它不起作用。
以下是json文件:
{
"time": {
"updated": "Aug 8, 2020 13:10:00 UTC",
"updatedISO": "2020-08-08T13:10:00+00:00",
"updateduk": "Aug 8, 2020 at 14:10 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi": {
"USD": {
"code": "USD",
"rate": "11,761.4920",
"description": "United States Dollar",
"rate_float": 11761.492
},
"BTC": {
"code": "BTC",
"rate": "1.0000",
"description": "Bitcoin",
"rate_float": 1
}
}
}
我想从上面的json文件中提取"rate":"11,761.4920“。
发布于 2020-08-08 13:18:50
问题就在这一行上:
const {rate} = data;您正在尝试使用rate提取破坏分配属性,但是该属性嵌套在两个对象中:
$ curl -s 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json' | jq '.'
{
"time": {
"updated": "Aug 8, 2020 13:09:00 UTC",
"updatedISO": "2020-08-08T13:09:00+00:00",
"updateduk": "Aug 8, 2020 at 14:09 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi": {
"USD": {
"code": "USD",
"rate": "11,769.7729", <------ here it is
"description": "United States Dollar",
"rate_float": 11769.7729
},
"BTC": {
"code": "BTC",
"rate": "1.0000",
"description": "Bitcoin",
"rate_float": 1
}
}
}
$正确的语法是:
const { bpi: { USD: { rate } } } = data;在这里,正在重写代码:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<body>
<h1>show me btc current rate</h1>
<p>current btc rate: <span id="btc_rate"></span>°</p>
<script>
const api_url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json';
async function getBTC()
{
const response = await fetch(api_url);
const data = await response.json();
const { bpi: { USD: { rate } } } = data;
document.getElementById('btc_rate').textContent = rate;
}
getBTC();
</script>
</body>
</html>
https://stackoverflow.com/questions/63315472
复制相似问题