Last active
May 17, 2018 15:41
-
-
Save ludvigeriksson/057a2c3b3997080cc744f0ffb57f3efd to your computer and use it in GitHub Desktop.
Read and write data to Google Sheets with a JSON API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Post method modified from https://github.com/jamiewilson/form-to-google-sheets | |
// Get method modified from https://ctrlq.org/code/20005-publish-json-google-spreadsheets | |
var sheetName = "Sheet1"; | |
var sheetId = "1-FuSfuJW..."; | |
function getSheet() { | |
var book = SpreadsheetApp.openById(sheetId); | |
var sheet = book.getSheetByName(sheetName); | |
return sheet; | |
} | |
function doGet(e) { | |
var sheet = getSheet(); | |
var json = sheetToJSON(sheet); | |
return ContentService | |
.createTextOutput(JSON.stringify(json)) | |
.setMimeType(ContentService.MimeType.JSON); | |
} | |
function doPost(e) { | |
var lock = LockService.getScriptLock(); | |
lock.tryLock(10000); | |
try { | |
var sheet = getSheet(); | |
var json = JSON.parse(e.postData.contents); | |
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; | |
var nextRow = sheet.getLastRow() + 1; | |
var newRow = headers.map(function(header) { | |
if (header === 'timestamp') { | |
return new Date(); | |
} else if (json[header]) { | |
return json[header]; | |
} | |
return ''; | |
}); | |
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]); | |
return ContentService | |
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow })) | |
.setMimeType(ContentService.MimeType.JSON); | |
} | |
catch (error) { | |
return ContentService | |
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': error })) | |
.setMimeType(ContentService.MimeType.JSON); | |
} | |
finally { | |
lock.releaseLock(); | |
} | |
} | |
function sheetToJSON(sheet) { | |
var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()); | |
var values = range.getValues(); | |
var headings = values.shift(); | |
var jsonArray = []; | |
for (var row in values) { | |
var json = {}; | |
for (var col in values[row]) { | |
json[headings[col]] = values[row][col]; | |
} | |
jsonArray.push(json); | |
} | |
return jsonArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Setup
Usage
Reading the data
Make a GET request to the address from step 7 in setup. An array of JSON objects, one for each row, will be returned.
Adding a new row
Make a POST request to the address from step 7 in setup. The body of the request should contain a JSON object representing the row to be added.