API call to drive.files.list failed with error: Invalid query

434 views
Skip to first unread message

Faustino Rodriguez

unread,
May 17, 2019, 8:22:42 AM5/17/19
to Google Apps Script Community
The following code returns "Invalid query" error if the file name contains double-quotes (")
It would probably fail as well for other 'special' characters, but I am only aware of the " so far

Question: How to avoid this error and find the file(s) with that name?

function getFilesByName(fileName, folderId) {
  var query = Utilities.formatString('"%s" in parents and trashed = false and mimeType != "application/vnd.google-apps.folder" and title = "%s"', folderId, fileName);
  var files, pageToken, items = [];
 
 
do {
    files
= Drive.Files.list({
      q
: query,
      maxResults
: 100,
      pageToken
: pageToken
   
});
   
   
if (files.items && files.items.length > 0) items = items.concat(files.items);
    pageToken
= files.nextPageToken;
 
} while (pageToken);
 
 
return items;
}

var files = getFilesByName('a filename with "quotes" within?', 'root');

Thanks, Fausto

Eric Koleda

unread,
May 22, 2019, 8:58:54 AM5/22/19
to Google Apps Script Community
Since a double quote is a special character in the query syntax, you just need to escape it with a backslash first:

filename.replace(/"/g, '\\"')

- Eric

Faustino Rodriguez

unread,
May 22, 2019, 9:14:46 AM5/22/19
to Google Apps Script Community
you are a genius @Eric !! 
- I was intending something 'like' that, but using only one \ 

I am really glad to have you around on this group
thanks again
Reply all
Reply to author
Forward
0 new messages