Home > Software design >  Fetch data via GS - response code 200 but data always "undefined"
Fetch data via GS - response code 200 but data always "undefined"

Time:11-03

I try to fetch the data given by https://api.llama.fi/charts/Ethereum

It looks like

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

when I open it in chrome.

In python with urllib.request.urlopen() it works fine.

Here in Google Sheets I try

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())
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Here data = 200, but data2 = undefined. I think it is a newbie question, but I am unfamiliar with JS or GS.

Thanks for your help!

Best,

Dominik

CodePudding user response:

You can access the data as JSON object by parsing the ContentText as JSON, then you can iterate the data with a for or use it in any other way you need.

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)
  }
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related