Skip to content

Instantly share code, notes, and snippets.

@kristian-lifelike
Last active September 21, 2017 10:46
Show Gist options
  • Save kristian-lifelike/7414269 to your computer and use it in GitHub Desktop.
Save kristian-lifelike/7414269 to your computer and use it in GitHub Desktop.
Copy doc JSON exporter for Google Drive spreadsheets.
/*
Copy doc JSON exporter for Google Drive spreadsheets.
Instructions:
1. Open the copy doc spreadsheet
2. Make sure the first row contains a column with the value “id” and that there’s at least one column with a locale value
2. Go to Tools/Script Editor…
3. (Optional) create a new script file and name it something funny
4. Paste the code from this file
5. Click save and name the project (“JSON Exporter” or whatever)
6. Reload the spreadsheet and the “Export JSON” menu should appear
7. You might have to approve the app the first time you use it
*/
//Constants
//var FORMAT_ONELINE = 'One-line';
var FORMAT_MULTILINE = 'Multi-line';
var FORMAT_PRETTY = 'Pretty';
var STRUCTURE_LIST = 'List';
var STRUCTURE_HASH = 'Hash (keyed by "id" column)';
// Defaults for this particular spreadsheet, change as desired
var DEFAULT_FORMAT = FORMAT_PRETTY;
var DEFAULT_STRUCTURE = STRUCTURE_HASH;
var _selectedLocale = 'none';
/* ==========================================================================
Initialize
========================================================================== */
/**
* Automatically called when a spreadsheet is opened
* Generates the "Export JSON" menu
* @return {void}
*/
function onOpen() {
var doc,
menuEntries;
menuEntries = [
{
name: "Export Specific Locale",
functionName: "chooseLocale"
},
null,
{
name: "Export All Locales",
functionName: "exportSheet"
},
{
name: "Export All Locales with String keys",
functionName: "exportSheetSimple"
}
];
doc = SpreadsheetApp.getActiveSpreadsheet();
doc.addMenu("Export JSON", menuEntries);
}
/* ==========================================================================
Choose locale
========================================================================== */
function chooseLocale(){
var doc,
app,
sheet,
headersRange,
headers,
locales,
grid;
doc = SpreadsheetApp.getActiveSpreadsheet();
sheet = doc.getActiveSheet();
headersRange = sheet.getRange(1, 1, 1, sheet.getMaxColumns());
headers = headersRange.getValues()[0];
locales = [];
for(var i = 0; i < headers.length; i++){
if(headers[i] && headers[i] !== 'id'){
locales.push(headers[i]);
}
}
app = UiApp.createApplication().setTitle('Select Locale');
grid = app.createGrid(4, 2);
grid.setWidget(0, 0, makeLabel(app, 'Export JSON for Locale:'));
grid.setWidget(0, 1, makeListBox(app, 'locale', locales));
grid.setWidget(3, 0, makeButton(app, grid, 'Export', 'exportSheet'));
grid.setWidget(3, 1, makeButton(app, grid, 'Export with String keys', 'exportSheetSimple'));
app.add(grid);
doc.show(app);
}
/* ==========================================================================
Export sheet
========================================================================== */
function exportSheet(e) {
_selectedLocale = e && e.parameter.locale || 'none';
parseSheet_(false, e);
}
function exportSheetSimple(e) {
_selectedLocale = e && e.parameter.locale || 'none';
parseSheet_(true, e);
}
function getExportOptions(e) {
var options = {};
options.format = e && e.parameter.format || DEFAULT_FORMAT;
options.structure = e && e.parameter.structure || DEFAULT_STRUCTURE;
var cache = CacheService.getPublicCache();
cache.put('format', options.format);
cache.put('structure', options.structure);
//Logger.log(options);
return options;
}
function parseSheet_(useSimple, e){
var doc,
sheet,
rowsData,
json;
doc = SpreadsheetApp.getActiveSpreadsheet();
sheet = doc.getActiveSheet();
rowsData = getRowsData_(sheet, getExportOptions(e), useSimple);
json = makeJSON_(rowsData, getExportOptions(e));
return displayText_(json);
}
/* ==========================================================================
Parse sheet
========================================================================== */
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData_(sheet, options, useSimple) {
var headersRange,
headers,
dataRange,
objects,
objectsById;
headersRange = sheet.getRange(1, 1, 1, sheet.getMaxColumns());
headers = headersRange.getValues()[0];
dataRange = sheet.getRange(1+1, 1, sheet.getMaxRows(), sheet.getMaxColumns());
//var objects = getObjects_(dataRange.getValues(), normalizeHeaders_(headers));
objects = getObjects_(dataRange.getValues(), headers);
if(options.structure === STRUCTURE_HASH) {
objectsById = {};
if(useSimple){
if(_selectedLocale === 'none'){
objectsById = getAllObjectsByIdSimple_(headers, objects);
} else {
objectsById = getObjectsOfLocaleSimple_(objects);
}
} else {
if(_selectedLocale === 'none'){
objectsById = getAllObjectsById_(headers, objects);
} else {
objectsById = getObjectsOfLocale_(objects);
}
}
return objectsById;
} else {
return objects;
}
}
function getAllObjectsById_(headers, objects){
var obj = {},
idParsed,
idParts,
currentLevel;
for(var i = 0; i < headers.length; i++){
if(headers[i] && headers[i] !== 'id'){
obj[headers[i]] = {};
}
}
objects.forEach(function(object) {
for(var prop in object){
if(prop && prop !== 'id'){
idParsed = object.id.replace(/ /g, '');
idParts = idParsed.split('.');
currentLevel = obj[prop];
for(var i = 0; i < idParts.length; i++){
if(i === idParts.length-1){
currentLevel[idParts[i]] = object[prop];
} else {
currentLevel[idParts[i]] = currentLevel[idParts[i]] || {};
currentLevel = currentLevel[idParts[i]];
}
}
}
}
});
return obj;
}
function getObjectsOfLocale_(objects){
var obj = {},
idParsed,
idParts,
currentLevel;
objects.forEach(function(object) {
for (var prop in object){
if(prop === _selectedLocale){
idParsed = object.id.replace(/ /g, '');
idParts = idParsed.split('.');
currentLevel = obj;
for(var i = 0; i < idParts.length; i++){
if(i === idParts.length-1){
currentLevel[idParts[i]] = object[prop];
} else {
currentLevel[idParts[i]] = currentLevel[idParts[i]] || {};
currentLevel = currentLevel[idParts[i]];
}
}
}
}
});
return obj;
}
function getAllObjectsByIdSimple_(headers, objects){
var obj = {};
for(var i = 0; i < headers.length; i++){
if(headers[i] && headers[i] !== 'id'){
obj[headers[i]] = {};
}
};
objects.forEach(function(object) {
for(var prop in object){
if(prop !== 'id'){
obj[prop][object.id] = object[prop];
}
}
});
return obj;
}
function getObjectsOfLocaleSimple_(objects){
var obj = {};
objects.forEach(function(object) {
for(var prop in object){
if(prop === _selectedLocale){
//obj[prop][object.id] = object[prop];
obj[object.id] = object[prop];
}
}
});
return obj;
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects_(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty_(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
function makeJSON_(object, options) {
if (options.format == FORMAT_PRETTY) {
var jsonString = JSON.stringify(object, null, 4);
} else if (options.format == FORMAT_MULTILINE) {
var jsonString = Utilities.jsonStringify(object);
jsonString = jsonString.replace(/},/gi, '},\n');
jsonString = prettyJSON.replace(/":\[{"/gi, '":\n[{"');
jsonString = prettyJSON.replace(/}\],/gi, '}],\n');
} else {
var jsonString = Utilities.jsonStringify(object);
}
return jsonString;
}
/* ==========================================================================
Methods for creating UI in spreadsheet
========================================================================== */
function displayText_(text) {
var app = UiApp.createApplication().setTitle('Exported JSON');
app.add(makeTextBox(app, 'json'));
app.getElementById('json').setText(text);
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.show(app);
return app;
}
function makeLabel(app, text, id) {
var lb = app.createLabel(text);
if (id) lb.setId(id);
return lb;
}
function makeListBox(app, name, items) {
var listBox = app.createListBox().setId(name).setName(name);
listBox.setVisibleItemCount(1);
var cache = CacheService.getPublicCache();
var selectedValue = cache.get(name);
//Logger.log(selectedValue);
for (var i = 0; i < items.length; i++) {
listBox.addItem(items[i]);
if (items[1] == selectedValue) {
listBox.setSelectedIndex(i);
}
}
return listBox;
}
function makeButton(app, parent, name, callback) {
var button = app.createButton(name);
app.add(button);
var handler = app.createServerClickHandler(callback).addCallbackElement(parent);;
button.addClickHandler(handler);
return button;
}
function makeTextBox(app, name) {
var textArea = app.createTextArea().setWidth('100%').setHeight('200px').setId(name).setName(name);
return textArea;
}
/* ==========================================================================
Helper methods
========================================================================== */
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders_(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader_(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader_(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum_(letter)) {
continue;
}
if (key.length == 0 && isDigit_(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty_(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum_(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit_(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit_(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose_(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment