Skip to content

Instantly share code, notes, and snippets.

@tusharacc
Last active January 15, 2016 18:45
Show Gist options
  • Save tusharacc/c4ca62961e808bec0786 to your computer and use it in GitHub Desktop.
Save tusharacc/c4ca62961e808bec0786 to your computer and use it in GitHub Desktop.
App Script to create a JSON from google spreadsheet
function doGet(e) {
var json = convertSheet2JsonText();
return ContentService.createTextOutput(JSON.stringify(json))
.setMimeType(ContentService.MimeType.JSON);
}
function convertSheet2JsonText() {
//XXXX is the id of the spreadsheet.ID is in the spreadsheet url - docs.google.com/spreadsheets/d/XXXX/editkkkk
var sheet = SpreadsheetApp.openById("XXXX").getActiveSheet();
var colStartIndex = 1;
var rowNum = 1;
var firstRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var firstRowValues = firstRange.getValues();
var titleColumns = firstRowValues[0];
// after the second line(data)
var lastRow = sheet.getLastRow();
var rowValues = [];
for(var rowIndex=2; rowIndex<=lastRow; rowIndex++) {
var colStartIndex = 1;
var rowNum = 1;
var range = sheet.getRange(rowIndex, colStartIndex, rowNum, sheet.getLastColumn());
var values = range.getValues();
rowValues.push(values[0]);
}
// create json
var jsonArray = [];
for(var i=0; i<rowValues.length; i++) {
var line = rowValues[i];
var json = new Object();
for(var j=0; j<titleColumns.length; j++) {
json[titleColumns[j]] = line[j];
}
jsonArray.push(json);
}
return jsonArray ;
}
@tusharacc
Copy link
Author

When the above code is published, google will provide a URL. When the URL is called it will return a JSON.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment