serveSheetAsJson(sheetName, {cacheSeconds}) returns a ContentService JSON response of a tab's rows as objects keyed by the header row, with CacheService in front so repeated requests do not read the sheet each time. It drops into doGet.
When to use
- A pricing table, changelog, or job board that lives in a sheet and should feed a website
- A static site or landing page that fetches one JSON URL
- Keeping page loads from hitting Sheets on every visit
How to use this snippet
Deploy the script as a web app (Execute as: Me, Who has access: Anyone). Anyone with the URL can read the tab, so only publish data that is meant to be public. The first row is the header; blank headers are skipped, and rows with every cell empty are dropped. cacheSeconds defaults to 300, is capped at 21,600 (six hours), and 0 turns caching off. The cache holds about 100 KB per entry, so a larger result is served without caching. For a standalone script, pass spreadsheetId.
/**
* Return a tab's rows as a JSON array of objects keyed by the header row,
* cached with CacheService. opts.cacheSeconds defaults to 300 (max 21600,
* 0 = no cache). opts.spreadsheetId is for standalone scripts. Throws if the
* tab is missing, so wrap it in try/catch in doGet. Results over about 90 KB
* are not cached.
*
* @param {string} sheetName
* @param {{cacheSeconds?: number, spreadsheetId?: string}} [opts]
* @return {GoogleAppsScript.Content.TextOutput}
*/
function serveSheetAsJson(sheetName, opts) {
opts = opts || {};
var ttl = opts.cacheSeconds == null ? 300 : Number(opts.cacheSeconds);
if (!isFinite(ttl) || ttl < 0) throw new Error('serveSheetAsJson: cacheSeconds must be 0 or more');
ttl = Math.min(Math.floor(ttl), 21600);
var name = String(sheetName == null ? '' : sheetName).trim();
if (!name) throw new Error('serveSheetAsJson: sheetName required');
var key = 'sheetjson:' + (opts.spreadsheetId || '') + ':' + name;
var cache = CacheService.getScriptCache();
var json = ttl > 0 ? cache.get(key) : null;
if (json == null) {
var ss = opts.spreadsheetId
? SpreadsheetApp.openById(opts.spreadsheetId)
: SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(name);
if (!sheet) throw new Error('serveSheetAsJson: no tab named "' + name + '"');
var values = sheet.getDataRange().getValues();
var headers = values.length ? values[0].map(function (h) { return String(h).trim(); }) : [];
var items = [];
for (var r = 1; r < values.length; r++) {
var obj = {};
var any = false;
for (var c = 0; c < headers.length; c++) {
if (!headers[c]) continue;
obj[headers[c]] = values[r][c];
if (values[r][c] !== '' && values[r][c] != null) any = true;
}
if (any) items.push(obj);
}
json = JSON.stringify(items);
if (ttl > 0 && json.length < 90000) {
try { cache.put(key, json, ttl); } catch (e) {}
}
}
return ContentService.createTextOutput(json).setMimeType(ContentService.MimeType.JSON);
}
Example
function doGet(e) {
try {
return serveSheetAsJson('Pricing', { cacheSeconds: 600 });
} catch (err) {
return jsonErr(err.message || String(err), 500);
}
}
jsonErr comes from JSON OK / ERR helpers. A new version of the script needs a new deployment version before the web app serves it. Pin a stable web app URL with versioned deployments shows how to keep the URL the same.
Notes
- After you edit the sheet, the old JSON can be served until the cache expires. Use a short
cacheSecondswhile you are testing. - Dates are returned as ISO strings. Numbers stay numbers.
- If a browser blocks the request from your page, fetch the URL when you build the site instead of at page load.
Happy Coding!
