Utilities.parseCsv()'无法解析文本'(Google Apps脚本) [英] Utilities.parseCsv() 'Could not parse text' (Google Apps Script)

查看:69
本文介绍了Utilities.parseCsv()'无法解析文本'(Google Apps脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑,因为它在更早的时候就起作用了,我不知道为什么现在它坏了.我有要解析的CSV文件.我正在使用以下代码访问它们:

I'm really confused because this was working earlier and I don't know why it is broken now. I've got CSV files that I'm trying to parse. I'm accessing them using the following code:

var file = DriveApp.getFileById(fileID);
var csv = file.getBlob().getDataAsString();
var data = Utilities.parseCsv(csv);

在第三行崩溃.调试时,我看到一切看起来都很正常... file是一个对象,csv是一个字符串,基于预览,我认为该格式对于CSV来说是正确的('header1,header2,header3 data1,data2,data3 data4,data5,data6...'等).但是,然后data是未定义的.是什么导致此错误?我在网上找不到太多东西,调试也没有为我提供任何很好的见识.

It crashes on that 3rd line. When debugging, I see everything looks normal... file is an object, csv is a string and based on the preview I think the format looks correct for a CSV ('header1,header2,header3 data1,data2,data3 data4,data5,data6...' etc). Then, however, data is undefined. What could be causing this error? I'm not finding much online and debugging didn't provide me with any good insight.

CSV中是否存在某些特殊符号可能会破坏此功能? CSV数据中有'"符号...但是我不知道为什么这很重要.

Are there particular symbols in the CSV that would break this function perhaps? There are ' and " symbols in the CSV data... but I don't know why that should matter.

更新: 我的文件有大约16000行.我目前正在分阶段尝试解决这个问题.但这不是引号;我对解析器进行了如下测试,并按预期工作:

UPDATE: My file in question has about 16000 lines. I'm currently going through it in segments trying to narrow down the problem. But it isn't quotes; I ran a test with the parser as follows and it worked as expected:

function myFunction() {
  var a = 'test""123,456\n';
  var b = "abc' 'def,ghi\n";
  var h = 'x,y\n';
  var str = h+a+b;
  var csv = Utilities.parseCsv(str);
  Logger.log(str);
  Logger.log(csv);
}

日志文件如下所示(预期):

The log file looked like this (expected):

x,y
test""123,456
abc' 'def,ghi

[[x, y], [test""123, 456], [abc' 'def, ghi]]

如果您还有其他想法要测试可能导致这种情况的原因,我可以对其进行测试.

If you have any more ideas to test as to what might be causing this, I can test them.

推荐答案

我今天正在处理相同的问题,发现某些行末尾的空格导致解析器失败.我使用以下正则表达式解决了这个问题:csvString.replace(/[ \t]+$/gm, '')

I was dealing with the same problem today and discovered that trailing spaces at the end of some lines were causing the parser to fail. I resolved this with this regular expression: csvString.replace(/[ \t]+$/gm, '')

这篇关于Utilities.parseCsv()'无法解析文本'(Google Apps脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆