Example JavaScript code to parse CSV data

前端 未结 12 1723
梦谈多话
梦谈多话 2020-11-21 07:58

Where could I find some JavaScript code to parse CSV data?

12条回答
  •  日久生厌
    2020-11-21 08:44

    Here's my PEG(.js) grammar that seems to do ok at RFC 4180 (i.e. it handles the examples at http://en.wikipedia.org/wiki/Comma-separated_values):

    start
      = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }
    
    line
      = first:field rest:("," text:field { return text; })*
        & { return !!first || rest.length; } // ignore blank lines
        { rest.unshift(first); return rest; }
    
    field
      = '"' text:char* '"' { return text.join(''); }
      / text:[^\n\r,]* { return text.join(''); }
    
    char
      = '"' '"' { return '"'; }
      / [^"]
    

    Try it out at http://jsfiddle.net/knvzk/10 or http://pegjs.majda.cz/online. Download the generated parser at https://gist.github.com/3362830.

提交回复
热议问题