Search code examples
jsongoogle-apps-scriptgoogle-apps-script-editor

How to convert all my data (files and folders) into a JSON file


Using Apps Script I want to know how to convert all my data i.e all my files and folders and convert it into a json file.


Solution

  • It's not clear from your question what you want to do with the files and folder so as a starter if you wanted to record the names of the files and folders list them in JSON format then the following code would return the names of the files and folders in Drive.

    var filesArr = [];
    var foldersArr = [];
    var filesFoldersObj = {};
    
    function doGet(request){
      var myJSON = getFilesFoldersToJSON();
      // return JSON text with the appropriate Media Type
      return ContentService.createTextOutput(myJSON).setMimeType(ContentService.MimeType.JSON);
    
    }
    
    function getFilesFoldersToJSON() {
    
      // Get the name of every file in Drive.
      var files = DriveApp.getFiles();
      while (files.hasNext()) {
        var file = files.next();
        filesArr.push(file.getName());
      }
      // create json string of file names
      var filesJSON = JSON.stringify(filesArr);
    
      // Get the name of every folder in Drive.
      var folders = DriveApp.getFolders();
      while (folders.hasNext()) {
        var folder = folders.next();
        foldersArr.push(folder.getName());
      }
        // create json string of folder names
      var foldersJSON = JSON.stringify(foldersArr);
    
      filesFoldersObj['files'] = filesArr;
      filesFoldersObj['folders'] = foldersArr;
      Logger.log(filesFoldersObj);
      var myJSON = JSON.stringify(filesFoldersObj);
      // log myJSON to check it - remove or comment out after checking...
      Logger.log(myJSON);
      return myJSON;
    }
    

    to produce JSON such as this...

    {
    "files": [
    "Files and Folders to JSON",
    "Test File 6",
    "Test File 5",
    "PDF File 6.pdf",
    "PDF File 5.pdf",
    "PDF File 4.pdf",
    "PDF File 3.pdf",
    "PDF File 2.pdf",
    "PDF File 1.pdf",
    "Test File 1",
    "Test File 2",
    "Test File 3",
    "Test File 4",
    "Getting started"
    ],
    "folders": [
    "Test Folder 6",
    "Test Folder 5",
    "Test Folder 2",
    "Test Folder 1",
    "Test Folder 4",
    "Test Folder 3"
    ]
    }