【问题标题】:Why is this UrlFetch function not working properly?为什么这个 UrlFetch 函数不能正常工作?
【发布时间】:2017-07-09 14:45:49
【问题描述】:

这是我试图通过我的 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"
    }
]

【问题讨论】:

  • 它做错了什么?
  • 它没有返回我希望获得的“price_btc”...

标签: javascript fetch urlfetch


【解决方案1】:

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

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

【讨论】:

  • 您好,感谢您的快速回复,但仍然无法正常工作 =/ 我试过了:html[0]["price_btc"], html[6]["price_btc"], html[" price_btc"][0] 和 html[6]。他们都没有工作......
  • @Thales454 如果 JSON 如上所示,它应该可以工作。 console.log(html[0]) 显示什么?
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    return html[0].price_btc;
    

    成功了,谢谢大家!

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 2023-02-20
      • 1970-01-01
      相关资源
      最近更新 更多