Skip to content

Instantly share code, notes, and snippets.

@rheajt
Last active July 7, 2016 16:51
Show Gist options
  • Save rheajt/f5790b603f6f7ac8b6a5e858fc85efb7 to your computer and use it in GitHub Desktop.
Save rheajt/f5790b603f6f7ac8b6a5e858fc85efb7 to your computer and use it in GitHub Desktop.
a simple way to turn your google sheet into a json object

Turn your Google Sheet into a JSONP service

  1. Copy the above code into the script editor
  2. Replace 'SHEET_ID_TO_SERVE' with the key to the sheet you are trying to serve as JSON
  3. Deploy as a web application
  4. Copy the URL that is created
  5. At the end of the URL add '?prefix=?'
  6. Enjoy your new API!

I hope this is detailed enough description. If you are questions/comments/suggestions hit me up on twitter @rheajt

Any JS/Google Apps Script wizards out there capable of giving me suggestions? Send them to me!

function doGet(request) {
// get the sheet object of the sheet you are serving
var sheet = SpreadsheetApp.openById('SHEET_ID_TO_SERVE').getSheetByName('SHEET_NAME');
// get all the data from the sheet
var data = sheet.getSheetValues(1, 1, sheet.getLastRow(), sheet.getLastColumn());
// shift the first row from the data as the header row
var headers = data.shift();
// create an empty array to hold the objects you create
var dataArr = [];
data.forEach(function(each) {
var dataObj = {};
//create key/value pairs from your headers/data
for(var i = 0; i < headers.length; i++) {
dataObj[headers[i]] = each[i];
}
dataArr.push(dataObj);
});
// return the dataArr with the content service
return ContentService.createTextOutput(
request.parameters.prefix + '(' + JSON.stringify(dataArr) + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment