为什么这个UrlFetch功能无法正常工作?

时间:2017-07-09 14:45:50

标签: javascript fetch urlfetch

这是我尝试在Google电子表格图表上运行JavaScript工具的功能,该功能目前正在4个不同的网站上运行,在此示例中:

$ id是我的电子表格单元格中输入的值(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;
  }
}

这是UrlFetch返回的内容:

[
    {
        "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"
    }
]

3 个答案:

答案 0 :(得分:1)

看起来端点正在返回一个对象数组,因此如果要访问数组中的第一项,请将try块更改为:

try {
  return parseFloat(html[0]["price_btc"]);
}

答案 1 :(得分:0)

尝试html.price_btc或html [0] .price_btc

答案 2 :(得分:0)

return html[0].price_btc;

让它发挥作用,谢谢大家!