【问题标题】:Why is this CSV file not parsing to an array?为什么这个 CSV 文件不解析为数组?
【发布时间】:2014-03-09 10:01:08
【问题描述】:

我正在尝试将外部 csv 文件解析为 javascript 数组,该数组采用如下数据:

AL185,YAHOO/PA_AL185,1855
ATUK,GOOG/LON_ATUK,@UK PLC 
408,YAHOO/SZ_000408,*STJG 
ATTY,GOOG/PINK_ATTY,1-800-Attorney Inc- 

然后把它变成这样的数组:

var stocks = [
    ["STI,GOOG/NYSE_STI,SunTrust Banks"],
    ["AAPL,GOOG/NASDAQ_AAPL,Apple Inc"]
];

上面的代码应该可以正确解析,但是不知道为什么不工作

代码:

$('#test').submit(function (event) {
function CSVToArray(strData, strDelimiter) {
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");

    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
    (
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"),
        "gi");


    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [
        []
    ];

    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;


    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {

        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];

        // When the very first character of the data is a delimiter
        // (either field or row delimiter) the item *before* the delimiter
        // is an unquoted empty string. This empty string we need to add
        // before handling the delimiter (ub@abego.org)
        if (arrMatches.index == 0 && strMatchedDelimiter) {
            arrData[arrData.length - 1].push("");
        }

        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
        strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {

            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);

        }


        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {

            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(
            new RegExp("\"\"", "g"),
                "\"");

        } else {

            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];

        }


        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }

    // Return the parsed data.
    return (arrData);
}
var csv =
    'AL185,YAHOO/PA_AL185,1855'
    'AL185,YAHOO/PA_AL185,1855'
var array = CSVToArray(csv, "\n");
alert(array[0]);
event.preventDefault();
})

上面的函数属于:http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm

【问题讨论】:

  • 究竟是什么不起作用?预期的结果是什么?
  • 我希望这样的数组成为预期结果@pasty, var stock = [ ["STI,GOOG/NYSE_STI,SunTrust Banks"], ["AAPL,GOOG/NASDAQ_AAPL,Apple Inc" ] ];
  • 如果您的示例输入与您的预期输出匹配会更清楚。
  • 第三次问同样的问题...stackoverflow.com/questions/22280102/…
  • 这是在对 Nathan P 进行实验之后。

标签: javascript arrays parsing csv


【解决方案1】:

不要传递控制字符(“\n”)并将其插入到您的正则表达式中,并在它前面加上一个\,而是传递它的代表(“\\n”)并将其放入您的正则表达式中额外的领先。 (注意:为了让 SO 显示 2 个斜杠,这是您需要的,我必须在这篇文章的“源”中添加 3 个。)

【讨论】:

  • 当我尝试时,这不是以正确的格式发布数组。
猜你喜欢
  • 1970-01-01
  • 2011-07-11
  • 2013-05-01
  • 2014-10-19
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多