Last active
February 7, 2020 01:53
-
-
Save metanomial/5c45f69436fec088791768696ef77bcb to your computer and use it in GitHub Desktop.
Google Sheets as JSON Log
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
function doPost(e) { | |
if(e.postData == null) return output({ error: 'no_data' }); | |
try { | |
const entries = JSON.parse(e.postData.contents); | |
if(!Array.isArray(entries)) return output({ error: 'not_array' }); | |
if(!entries.length) return output({ error: 'empty_array' }); | |
entries.forEach(append); | |
return output({ success: entries.length }); | |
} catch(exception) { | |
return output({ | |
error: exception.name, | |
message: exception.message | |
}); | |
} | |
} | |
function doGet(e) { | |
const entries = SpreadsheetApp | |
.getActiveSheet() | |
.getRange('A:A') | |
.getDisplayValues() | |
.map(firstChild) | |
.map(parseJSON); | |
return output(entries); | |
} | |
function firstChild(array) { | |
return array[0]; | |
} | |
function parseJSON(string) { | |
try { | |
return JSON.parse(string); | |
} catch(exception) { | |
return { | |
error: exception.name, | |
message: exception.message | |
} | |
} | |
} | |
function output(target) { | |
const data = JSON.stringify(target); | |
return ContentService.createTextOutput(data); | |
} | |
function append(entry) { | |
const data = JSON.stringify(entry); | |
const sheet = SpreadsheetApp.getActiveSheet(); | |
sheet.appendRow(['']); | |
sheet.getRange(sheet.getLastRow() + 1, 1) | |
.setNumberFormat('@') | |
.setValue(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment