Google Drive AutomationDifficulty: Beginner⚡ On Demand or onEdit

Export Google Sheets Range to JSON File in Google Drive

Transforms a spreadsheet table into a structured JSON array of objects (using column headers as keys) and saves the file directly to Google Drive for frontend or mobile consumption.

Required OAuth Scopes: https://www.googleapis.com/auth/drive • https://www.googleapis.com/auth/spreadsheets
Code.gs (Apps Script V8 Runtime)
function exportSheetToJsonFile() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Products');
  const data = sheet.getDataRange().getValues();
  const headers = data[0];
  const jsonArray = [];
  
  for (let i = 1; i < data.length; i++) {
    const obj = {};
    for (let j = 0; j < headers.length; j++) {
      obj[headers[j]] = data[i][j];
    }
    jsonArray.push(obj);
  }
  
  const folder = DriveApp.getRootFolder();
  const fileContent = JSON.stringify(jsonArray, null, 2);
  folder.createFile('products.json', fileContent, MimeType.PLAIN_TEXT);
}

Line-by-Line Code Explanation

Line 2-4: Reads table rows and header strings.
Line 6-12: Maps each data row into a clean JavaScript key/value object.
Line 14-16: Serializes JSON with indentation and saves as a Drive file.

Step-by-Step Setup & Deployment

  1. Ensure Row 1 has clean column names.
  2. Run script to generate `products.json` in your Google Drive.

Best Practices for Quota & Rate Limit Management

When deploying this automation in Google Workspace, adhere to these operational principles:

  • Batch Reads & Writes: Never execute getValue() or setValue() inside loops. Read ranges into memory in 1 call, process arrays in V8 memory, and commit changes with a single setValues() call.
  • Execution Timeouts: Apps Script terminates scripts exceeding 6 minutes. For multi-thousand row datasets, implement batch pagination with resume timestamps stored in PropertiesService.
  • OAuth Permissions: Scope your manifest (appsscript.json) narrowly to prevent security prompts from alarming external team members.

Frequently Asked Questions

Is Google Apps Script completely free to use?

Yes. Google Apps Script is built into all free Google accounts and Google Workspace editions. There are no server fees or subscription costs for running scripts within daily quotas.

Can I run this script on an automated schedule without keeping my computer on?

Yes. Time-driven triggers execute on Google's cloud infrastructure. Your script will run reliably even when your computer is closed or offline.

More Google Drive Automation Snippets