Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google script - json into google sheet

I'm new to scripting and I would appreciate your help. I do apologize for what might be a simple question.

What I have is an api that gives json:

[{"id":"xyz","name":"xy"}, {"id":"zyx","name":"yx"}]

The above continues lets say for another 100 ids.

What I want is to put that into the cells in google spreadsheet.

What I have currently is:

var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rr = sh.getRange(3,2,100,5);

var id = "www.xyz.com/api";
var jsonData = UrlFetchApp.fetch(id);
var jsonString = jsonData.getContentText();
var idsearch = JSON.parse(jsonString);

for (var i = 1; i < idsearch.count; i++)
  {
     var cellid = rr.getCell(i,1);
     eventid.setValue(idsearch.results[i].id);
     var cellname = rr.getCell(i,2);
     eventname.setValue(idsearch.results[i].name);
  }

When I run the script, nothing happens. It doesnt return anything.

Did I make a mistake in the script? Is there an easier way to put all the json result into google sheet? Is there an example where I can look at to learn about what I'm trying to do?

Thank you very much.

like image 305
Az37 Avatar asked Dec 20 '22 02:12

Az37


1 Answers

I hope this simple code might help you.

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var sheet = ss.getActiveSheet();

  var dataSet = [
    {"id":"xyz","name":"xy"},
    {"id":"zyx","name":"yx"}
  ]; 
  var rows = [],
      data;

  for (i = 0; i < dataSet.length; i++) {
    data = dataSet[i];
    rows.push([data.id, data.name]);
  }

  dataRange = sheet.getRange(1, 1, rows.length, 2);
  dataRange.setValues(rows);

}

enter image description here

like image 159
wf9a5m75 Avatar answered Dec 28 '22 06:12

wf9a5m75