Example JavaScript code to parse CSV data

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

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

12条回答
  •  旧巷少年郎
    2020-11-21 08:42

    Here's another solution. This uses:

    • a coarse global regular expression for splitting the CSV string (which includes surrounding quotes and trailing commas)
    • fine-grained regular expression for cleaning up the surrounding quotes and trailing commas
    • also, has type correction differentiating strings, numbers and boolean values

    For the following input string:

    "This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true
    

    The code outputs:

    [
      "This is, a value",
      "Hello",
      4,
      -123,
      3.1415,
      "This is also, possible",
      true
    ]
    

    Here's my implementation of parseCSVLine() in a runnable code snippet:

    function parseCSVLine(text) {
      return text.match( /\s*(\".*?\"|'.*?'|[^,]+)\s*(,|$)/g ).map( function (text) {
        let m;
        if (m = text.match(/^\s*\"(.*?)\"\s*,?$/)) return m[1]; // Double Quoted Text
        if (m = text.match(/^\s*'(.*?)'\s*,?$/)) return m[1]; // Single Quoted Text
        if (m = text.match(/^\s*(true|false)\s*,?$/)) return m[1] === "true"; // Boolean
        if (m = text.match(/^\s*((?:\+|\-)?\d+)\s*,?$/)) return parseInt(m[1]); // Integer Number
        if (m = text.match(/^\s*((?:\+|\-)?\d*\.\d*)\s*,?$/)) return parseFloat(m[1]); // Floating Number
        if (m = text.match(/^\s*(.*?)\s*,?$/)) return m[1]; // Unquoted Text
        return text;
      } );
    }
    
    let data = `"This is\, a value",Hello,4,-123,3.1415,'This is also\, possible',true`;
    let obj = parseCSVLine(data);
    console.log( JSON.stringify( obj, undefined, 2 ) );

提交回复
热议问题