5
4

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 5 years have passed since last update.

JSでCSVをパースする

Posted at

CSVのパースは単純に考えるとこんな感じ

const simpleParseCSV=(csv)=>{
    return csv.split("\n").map((row)=>row.split(','));  
},

しかしCSVは値の中にコンマや改行やはたまたダブルクォーテーションが入ってたりもする
ダブルクォーテーションはあんまりないだろうけど
値にコンマや改行が入るケースというのは結構ある

ということでそれらに対応したCSVのパース処理

const parseCSV=(csv)=>{
    let tmp=[];
    csv=csv.replace(/("[^"]*")+/g,(match)=>{
        tmp.push(match.slice(1,-1).replace(/""/g,'"'));return '[TMP]';
    });
    return csv.split("\n").map((row)=>{
        return row.split(',').map((val)=>val==='[TMP]'?tmp.shift():val)
    });
};

ダブルクォーテーションで囲まれてない値に
ダブルクォーテーションがある場合に対応できてないけど
Excelから書き出してもPHPのfputcsvでもそうはならないので
そういうCSVはまずないものとしてそこは妥協

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?