问题
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:
$id is the imported value from my spreadsheet cell (belacoin)
function CoinmarketcapPrice($id) {
var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
var html = JSON.parse(response.getContentText());
try
{
return parseFloat(html["price_btc"]);
}
catch(err)
{
return null;
}
}
this is what that UrlFetch returns:
[
{
"id": "belacoin",
"name": "BelaCoin",
"symbol": "BELA",
"rank": "176",
"price_usd": "0.212823",
"price_btc": "0.00008400",
"24h_volume_usd": "534995.0",
"market_cap_usd": "7694903.0",
"available_supply": "36156350.0",
"total_supply": "36156350.0",
"percent_change_1h": "0.63",
"percent_change_24h": "1.88",
"percent_change_7d": "-17.03",
"last_updated": "1499549044"
}
]
回答1:
try html.price_btc or html[0].price_btc
回答2:
It looks like that endpoint is returning an array of objects, so if you want to access the first item in the array change your try block to:
try {
return parseFloat(html[0]["price_btc"]);
}
回答3:
return html[0].price_btc;
made it work, thank you all!
来源:https://stackoverflow.com/questions/44997630/why-is-this-urlfetch-function-not-working-properly