Home > Software design >  JSON import - Cannot read property 'length' of undefined
JSON import - Cannot read property 'length' of undefined

Time:01-03

I'm trying to import JSON via API into Google sheets but get the error

Cannot read property 'length' of undefined

Here is my code

function importRank(){
  url = 'https://public-api.solscan.io/token/holders?tokenAddress=sinjBMHhAuvywW3o87uXHswuRXb3c7TfqgAdocedtDj&offset=0&limit=max'
  var json = JSON.parse(UrlFetchApp.fetch(url).getContentText())
  var data = json.data.owner
  var data2 = json.data.rank
  var data3 = json.data.total
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('WalletRank')
  sh.getRange(2,1,data.length,data[0].length).setValues(data)
  sh.getRange(2,2,data2.length,data2[0].length).setValues(data2)
  sh.getRange(2,3,data3.length,data3[0].length).setValues(data3)
}

CodePudding user response:

Try

function importRank(){
  url = 'https://public-api.solscan.io/token/holders?tokenAddress=sinjBMHhAuvywW3o87uXHswuRXb3c7TfqgAdocedtDj&offset=0&limit=max'
  var json = JSON.parse(UrlFetchApp.fetch(url).getContentText())
  var data=[]
  Logger.log(json.total)
  json.data.forEach(function(x){
    data.push([x.owner,x.rank,x.amount])
  })
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('WalletRank')
  sh.getRange(2,1,data.length,data[0].length).setValues(data)
  sh.getRange(2,4).setValue(json.total)
}

enter image description here

Explanation

the structure is as follows

{"data":[
{"address":"__________","amount":________,"decimals":__,"owner":"___","rank":_},
...
],"total":_____}

that means that data is an array [] of multi elements which contains each of them {} address, amount, decimals, owner and rank

Reference

forEach

  • Related