1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

javascriptで簡単CSV解析

Last updated at Posted at 2020-10-11

関数1つでCSVを二次元配列に変換します。

  • ES3対応。
  • 区切り文字を変えればタブ区切りテキストでもOK。
  • 末尾に改行がなくてもOK。途中に改行だけの行があれば無視します。
  • " で囲ってあれば、改行や区切り文字が含まれていてもOK。
  • " を含めるならば "" を入れる。
  • バグがあったら教えてください。
// CSVをパース
function parseCsv(csvStr, delimiter) {
    var rowRegex = /(?:(?:"[^"]*")*[^\r\n"]*)+/g,
        colRegex = new RegExp('(?:(?:"[^"]*")*[^' + delimiter + '"]*)+', 'g'),
        rows = [],
        row, cells, cell, rowMaches, colMaches;
    //行を切り出す
    while ((rowMaches = rowRegex.exec(csvStr)) !== null) {
        if (rowMaches[0] !== '') {
            cells = [];
            row = rowMaches[0];
            //セルを切り出す
            while ((colMaches = colRegex.exec(row)) !== null) {
                cell = colMaches[0].replace(/^\s+|\s+$/g, '');
                if (cell.charAt(0) == '"' && cell.charAt(cell.length - 1) == '"') {
                    cell = cell.slice(1, -1);
                }
                cell = cell.replace(/""/g, '"');
                cells.push(cell);
                colRegex.lastIndex++; //一歩前へ!
            }
            rows.push(cells);
        }
        rowRegex.lastIndex++; //一歩前へ!
    }
    return rows;
}

// カンマ区切り
var str1 = "連番,氏名,氏名(カタカナ),性別,電話番号,生年月日\n" +
    "1,小平勝美,コダイラ カツミ,女,\"0993298298\",1987/07/12\n" +
    "2,沢井慶太,サワイ ケイタ,男,\"0881257342\",1986/10/25\n" +
    "3,神崎勝男,カンザキ カツオ,男,\"087946508\",1985/09/30\n" +
    "4,島津源治,シマヅ ゲンジ,男,\"0173059125\",1971/06/06\n" +
    "5,岩谷由姫,イワタニ ユキ,女,\"0970852069\",1999/09/07";

var data1 = parseCsv(str1, ",");
console.log(JSON.stringify(data1, null, '  '));

// タブ区切り
var str2 = "連番\t氏名\t氏名(カタカナ)\t性別\t電話番号\t生年月日\n" +
    "6\t合田郁美\tアイダ イクミ\t\t\"025775007\"\t1989/06/17\n" +
    "7\t梅原侑歩\tウメハラ ユウホ\t\t\"089975035\"\t1995/08/22\n" +
    "8\t吉野有香\tヨシノ ユカ\t\t\"0244902616\"\t1975/09/02\n" +
    "9\t松野時雄\tマツノ トキオ\t\t\"0982714767\"\t1978/06/15\n" +
    "10\t依田永遠\tイダ トワ\t\t\"0522081957\"\t1996/10/14";

var data2 = parseCsv(str2, "\t");
console.log(JSON.stringify(data2, null, '  '));
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?