Created
July 12, 2024 14:05
-
-
Save gordonnl/d3c911fd1be3ee2da06fd2bc9f934a1f to your computer and use it in GitHub Desktop.
Export Google Sheets Copy to Json - Apps Script
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
/* | |
Exports a multi-language copy deck into individual JSON files | |
Expects data in this format | |
Key | en | fr | |
--------------------------- | |
TITLE | Welcome | Bienvenue | |
Which exports en.js and fr.json | |
eg en.js: | |
{ | |
"TITLE": "Welcome | |
} | |
*/ | |
function exportJSON() { | |
const sheet = SpreadsheetApp.getActiveSheet(); | |
const ui = SpreadsheetApp.getUi(); | |
const range = sheet.getDataRange(); | |
const values = range.getValues(); // rows of columms | |
// Holds code of language | |
const languages = []; | |
// Holds objects of keys for each language | |
const copy = []; | |
values.forEach((row, rowIndex) => { | |
// Ignore empty row | |
if (!row || !row[0]) return; | |
// Use first row to create objects for each language | |
if (!rowIndex) { | |
row.forEach((value, columnIndex) => { | |
// Ignore first column (Key) | |
if (!columnIndex) return; | |
// Ignore empty cells | |
if (!value) return; | |
// Create empty object and store language code | |
languages[columnIndex - 1] = value; | |
copy[columnIndex - 1] = {}; | |
}); | |
return; | |
} | |
// if (rowIndex > 2) return; | |
let currentKey = ''; | |
row.forEach((value, columnIndex) => { | |
// Stores each row key from first column | |
if (!columnIndex) return (currentKey = value); | |
// Adds copy to each language copy object | |
copy[columnIndex - 1][currentKey] = value; | |
}); | |
}); | |
const htmlOutput = HtmlService.createHtmlOutput( | |
` | |
<script> | |
const languages = ${JSON.stringify(languages)}; | |
const copy = ${JSON.stringify(copy)}; | |
function timeout(t) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, t); | |
}); | |
} | |
languages.forEach(async (language, i) => { | |
await timeout(i * 100); | |
const elem = document.createElement('a'); | |
elem.href = 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(copy[i])); | |
elem.download = language + '.json'; | |
elem.click(); | |
if (i === languages.length - 1) google.script.host.close(); | |
}); | |
</script> | |
` | |
) | |
.setWidth(250) | |
.setHeight(100); | |
ui.showModalDialog(htmlOutput, 'Downloading JSON'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment