Save Google Sheet as JSON

The ExportSheetAsJSON() method will save the currently active sheet of a Google Spreadsheet as a JSON file and saves it to your Google Drive. The header (first row) are used as attributes.


/* From https://gist.github.com/IronistM/8be09ebd4c5a4a58c63b */

function exportSheetAsJSON() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var numCols = rows.getNumColumns();
  var values = rows.getValues();
  
  var output = "";
  output += "{\""+sheet.getName()+"\" : {\n";
  var header = values[0];
  for (var i = 1; i < numRows; i++) {
    if (i > 1) output += " , \n";
    var row = values[i];
    output += "\""+row[0]+"\" : {";
    for (var a = 1;a<numCols;a++){
      if (a > 1) output += " , ";
         output += "\""+header[a]+"\" : \""+row[a]+"\"";
    }
    output += "}";
    //Logger.log(row);
  }
  output += "\n}}";
  Logger.log(output);
  
  DriveApp.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
  
};