1
votes

I am trying to create a json of google spreadsheet in specific folder in google drive.

for example my google drive have folder named "temp" and it contains google spreadsheet i am then running google app script code from that spreadsheet.

here is the code

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);
};

above the code works perfectly but it always create json file in root folder of google drive instead of temp folder.

can anyone have solution for the above problem ?

1

1 Answers

1
votes

Try this:

  Logger.log(output); 

  var theFolder = DriveApp.getFoldersByName('temp');

  while (theFolder.hasNext()) {
   var folder = theFolder.next();
   Logger.log(folder.getName());
   folder.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
 }

};