首页 > 解决方案 > 通过 GS 获取数据 - 响应代码 200 但数据始终“未定义”

问题描述

我尝试获取https://api.llama.fi/charts/Ethereum给出的数据

看起来像

[{"date":"1546560000","totalLiquidityUSD":273845651.27077854},{"date":"1546646400","totalLiquidityUSD":288674544.41292274},{"date":"1546732800","totalLiquidityUSD":301742} "日期":"1546819200","totalLiquidityUSD":286168221.103729},{"日期":"1546905600","totalLiquidityUSD":285073686.76345384}, ...

当我在 chrome 中打开它时。

在 python 中urllib.request.urlopen()它工作正常。

在谷歌表格中我尝试

function myFunction() {
  var data = UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getResponseCode()
  var data2 = UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getContentText()
  console.log(UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getContentText())
}

这里 data = 200,但 data2 = undefined。我认为这是一个新手问题,但我对JS或GS不熟悉。

谢谢你的帮助!

最好的,

多米尼克

标签: javascriptgoogle-apps-scriptweb-scrapinggoogle-sheetsurlfetch

解决方案


您可以通过将 ContentText 解析为 JSON 来以 JSON 对象的形式访问数据,然后您可以使用 for 迭代数据或以您需要的任何其他方式使用它。

function myFunction() {
  var response = UrlFetchApp.fetch("https://api.llama.fi/charts/Ethereum").getContentText()
  
  var data = JSON.parse(response);
  for(const d of data) {
    console.log("DATE: " + d.date)
    console.log("LIQUIDITY: " + d.totalLiquidityUSD)
  }
}


推荐阅读