Search code examples
javascriptgoogle-apps-scriptgoogle-admin-sdk

Google Apps Script split('\n') does not work with data from the Goggle Admin Directory


I am retrieving user data via the Google Admin Directory where I stored some data in a customer schema. In one field of this customer data I store a string which contains \n so I would like to split this into an array. But for some reason this does not work and I would like to understand why and how to fix this. This is the setup:

I go to the G Suite Admin Panel and go to one user's schema and enter the string: Doesnt \n work.

In the Apps script I retrieve that data and split it. But it does not split it into an array:

function listAllUsers(oa) {
var pageToken, page;
var userDatas = [];
do {
page = AdminDirectory.Users.list({
  customer: 'my_customer',
  query: 'orgUnitPath:'+oa,
  orderBy: 'givenName',
  projection: 'full',
  maxResults: 100,
  pageToken: pageToken
});

var theData ='';
var users = page.users;
if (users) {
  for (var i = 0; i < users.length; i++) {
    var user = users[i];
    

    if( (typeof user.customSchemas !== "undefined") && ('myCustomSchema' in user.customSchemas)){
 
     theData = user.customSchemas.myCustomSchema.myCustomSchemaField;
     Logger.log(theData); //  this shows Doesnt \n work
     var splitarray = theData.split('\n'); // this shows this shows [Doesnt \n work]
     theData = 'Doesnt \n work';
     splitarray = theData.split('\n'); // this shows [ Doesnt , work] which is correct

    }
    else{
      Logger.log("no data");
    }

}
pageToken = page.nextPageToken;
} while (pageToken);
Logger.log(userDatas);
return userDatas;
}

How is that possible? Do I have to do some encoding first?


Solution

  • I suspect the string actually has a backslash followed by the letter n, rather than having a newline in it. E.g., in string literal terms: "Doesnt \\n work" (which, when printed, looks like Doesnt \n work).

    You can prove this by doing this:

    Logger.log(theData.indexOf("\\"));
    

    ...which will give you the index at which a backslash is found (-1 if there isn't any), or this:

    Logger.log(theData.split("").map(function(ch) { return ch + "(" + ch.charCodeAt(0) + ")";}).join(", "));
    

    ...which shows you each code unit in the string and its character code.