Why is this UrlFetch function not working properly?

假如想象 提交于 2019-12-13 03:34:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!