Skip to content

Instantly share code, notes, and snippets.

@jonobr1
Last active April 26, 2024 15:41
Show Gist options
  • Save jonobr1/45fc5f41a219153aaa18 to your computer and use it in GitHub Desktop.
Save jonobr1/45fc5f41a219153aaa18 to your computer and use it in GitHub Desktop.
A node.js script to convert a Google Sheet into a JSON object
/**
* Simple Node.js script to turn a specific page on a Google Sheet
* into a JSON object for the main purpose of HTML Templating.
*
* @author jonobr1 / http://jonobr1.com
*
*/
var https = require('https');
var path = require('path');
var fs = require('fs');
var format = 'tsv'; // Format you'd like to parse. `tsv` or `csv`
var id = 'GOOGLE_SHEET_ID'; // The Google Sheet ID found in the URL of your Google Sheet.
var sheetId = 0; // The Page ID of the Sheet you'd like to export. Found as `gid` in the URL.
https.get('https://docs.google.com/spreadsheets/d/' + id + '/export?format=' + format + '&id=' + id + '&gid=' + sheetId, function(resp) {
var body = '';
resp
.on('data', function(data) {
body += ab2str(data);
})
.on('end', function() {
var json = [];
var rows = body.split(/\r\n/i);
for (var i = 0; i < rows.length; i++) {
json.push(rows[i].split(/\t/i));
}
fs.writeFileSync(path.resolve(__dirname, './sheet.json'), JSON.stringify(json));
console.log('Generated sheet.json');
});
});
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
@jonobr1
Copy link
Author

jonobr1 commented May 2, 2022

I could be wrong, but I believe the latest version of Google Sheets does not allow you to access spreadsheet content in this way anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment