如何将 json 文件添加到 Google Apps 脚本中的特定文件夹?

How to add json file to specific folder in Google Apps Script?

此代码运行良好,但文件转到根文件夹。我在互联网上没有找到任何有用的...

function saveAsJSON() {
  var blob,file,fileSets,obj;
  
  obj = {//Object literal for testing purposes
    key:"value"
  }

/**
 * Creates a file in the users Google Drive
 */
  
  fileSets = {
    title: 'file.json',
    mimeType: 'application/json'
  };
  
  blob = Utilities.newBlob(JSON.stringify(obj), "application/vnd.google-apps.script+json");
  file = Drive.Files.insert(fileSets, blob);
  Logger.log('ID: %s, File size (bytes): %s, type: %s', file.id, file.fileSize, file.mimeType);

}

回答

您需要在 fileSets 中使用 parents 属性 并输入所需的驱动器文件夹 ID as seen from this sample documentation。请参阅下面这个经过调整的脚本:

调整脚本

function saveAsJSON() {
  var blob,file,fileSets,obj;
  
  obj = {//Object literal for testing purposes
    key:"value"
  }

/**
 * Creates a file in the users Google Drive
 */
  
  fileSets = {
    title: 'file.json',
    mimeType: 'application/json',
    parents:[{"id":"THE_FOLDER_ID"}] //Add your FOLDER_ID here
  };
  
  blob = Utilities.newBlob(JSON.stringify(obj), "application/vnd.google-apps.script+json");
  file = Drive.Files.insert(fileSets, blob);
  Logger.log('ID: %s, File size (bytes): %s, type: %s', file.id, file.fileSize, file.mimeType);
}

示例演示

  • 文件已保存到我的样本tempFolder: