Skip to content

Instantly share code, notes, and snippets.

@NaturalizerINA
Last active March 11, 2021 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaturalizerINA/48babb3f4acd9c283343b1309b21f888 to your computer and use it in GitHub Desktop.
Save NaturalizerINA/48babb3f4acd9c283343b1309b21f888 to your computer and use it in GitHub Desktop.
Create the script to get the data form google sheets
function doGet(request){
//initialize the spreadsheet id
var ss = SpreadsheetApp.openById(''); //Fill the ID
//get the column data
var data = ss.getDataRange().getValues();
//initialize the variable of 'data' rows
var jsonArray = [];
// loop the row data
// the "var i = 1" because the data row is loop from second row,
// the first row is just for labeling our column name in spreadsheet, like id, name and majors, so I start with i = 1
for (var i = 1; i < data.length; i++) {
//initialize the variable to wrap the whole of json output
var jsonObject = {};
//constraint the filled column from the first row(data[0])
var colConstraint = data[0].length;
//loop the col data
for(var col = 0; col < colConstraint; col++){
//first row should be like this :
//col 0 {title : value [row i]}
//col 1 {title : value [row i]}
jsonObject[data[0][col]] = data[i][col];
}
//create an Array from Json Object
jsonArray.push(jsonObject);
}
//checking the data, is empty or not
if(jsonArray.length>0){
var JSONString = JSON.stringify(
{
'status': '200',
'message': 'Success to fetch data',
'data': jsonArray,
}
);
} else {
var JSONString = JSON.stringify(
{
'status': '201',
'message': 'Data empty',
'data': jsonArray,
}
);
}
//create the json output
var JSONOutput = ContentService.createTextOutput(JSONString);
JSONOutput.setMimeType(ContentService.MimeType.JSON);
return JSONOutput;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment