问题描述
我正在通过Google Admin Directory检索用户数据,在那里我在客户模式中存储了一些数据。在此客户数据的一个字段中,我存储了一个包含\n
的字符串,因此我想将其拆分为一个数组。但是出于某种原因,这是行不通的,我想了解为什么以及如何解决此问题。这是设置:
我转到G Suite管理面板,转到一个用户的架构,然后输入字符串:Doesnt \n work
。
在Apps脚本中,我检索该数据并将其拆分。但是它不会将其拆分为数组:
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;
}
那怎么可能?我必须先做一些编码吗?
解决方法
我怀疑该字符串实际上带有反斜杠,后跟字母n
,而不是其中包含换行符。例如,以字符串文字形式表示:"Doesnt \\n work"
(在打印时看起来像Doesnt \n work
)。
您可以通过以下方法证明这一点:
Logger.log(theData.indexOf("\\"));
...这将为您提供找到反斜杠的索引(如果没有反斜杠,则为-1
),或者这样的
Logger.log(theData.split("").map(function(ch) { return ch + "(" + ch.charCodeAt(0) + ")";}).join(","));
...显示字符串中的每个代码单元及其字符代码。