Last active
October 3, 2021 20:19
-
-
Save qmacro/6199973 to your computer and use it in GitHub Desktop.
SheetAsJSON - expose a Google spreadsheet (with a header row) as JSON - See https://qmacro.org/2013/10/04/sheetasjson-google-spreadsheet-data-as-json/ for a writeup
This file contains hidden or 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
function doGet(request) { | |
var output = ContentService.createTextOutput(); | |
var data = {}; | |
var id = request.parameters.id; | |
var sheet = request.parameters.sheet; | |
var ss = SpreadsheetApp.openById(id); | |
data["records"] = readData_(ss, sheet); | |
var callback = request.parameters.callback; | |
if (callback == undefined) { | |
output.setContent(JSON.stringify(data)); | |
} | |
else { | |
output.setContent(callback + "(" + JSON.stringify(data) + ")"); | |
} | |
output.setMimeType(ContentService.MimeType.JSON); | |
return output; | |
} | |
function readData_(ss, sheetname, properties) { | |
if (typeof properties == "undefined") { | |
properties = getHeaderRow_(ss, sheetname); | |
properties = properties.map(function(p) { return p.replace(/\s+/g, '_'); }); | |
} | |
var rows = getDataRows_(ss, sheetname); | |
var data = []; | |
for (var r = 0, l = rows.length; r < l; r++) { | |
var row = rows[r]; | |
var record = {}; | |
for (var p in properties) { | |
record[properties[p]] = row[p]; | |
} | |
data.push(record); | |
} | |
return data; | |
} | |
function getDataRows_(ss, sheetname) { | |
var sh = ss.getSheetByName(sheetname); | |
return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues(); | |
} | |
function getHeaderRow_(ss, sheetname) { | |
var sh = ss.getSheetByName(sheetname); | |
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment