Example JavaScript code to parse CSV data

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

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

相关标签:
12条回答
  • 2020-11-21 08:21

    csvToArray v1.3

    A compact (645 bytes), but compliant function to convert a CSV string into a 2D array, conforming to the RFC4180 standard.

    https://code.google.com/archive/p/csv-to-array/downloads

    Common Usage: jQuery

     $.ajax({
            url: "test.csv",
            dataType: 'text',
            cache: false
     }).done(function(csvAsString){
            csvAsArray=csvAsString.csvToArray();
     });
    

    Common usage: JavaScript

    csvAsArray = csvAsString.csvToArray();
    

    Override field separator

    csvAsArray = csvAsString.csvToArray("|");
    

    Override record separator

    csvAsArray = csvAsString.csvToArray("", "#");
    

    Override Skip Header

    csvAsArray = csvAsString.csvToArray("", "", 1);
    

    Override all

    csvAsArray = csvAsString.csvToArray("|", "#", 1);
    
    0 讨论(0)
  • 2020-11-21 08:23

    jQuery-CSV

    It's a jQuery plugin designed to work as an end-to-end solution for parsing CSV into JavaScript data. It handles every single edge case presented in RFC 4180, as well as some that pop up for Excel/Google spreadsheet exports (i.e., mostly involving null values) that the specification is missing.

    Example:

    track,artist,album,year

    Dangerous,'Busta Rhymes','When Disaster Strikes',1997

    // Calling this
    music = $.csv.toArrays(csv)
    
    // Outputs...
    [
      ["track", "artist", "album", "year"],
      ["Dangerous", "Busta Rhymes", "When Disaster Strikes", "1997"]
    ]
    
    console.log(music[1][2]) // Outputs: 'When Disaster Strikes'
    

    Update:

    Oh yeah, I should also probably mention that it's completely configurable.

    music = $.csv.toArrays(csv, {
      delimiter: "'", // Sets a custom value delimiter character
      separator: ';', // Sets a custom field separator character
    });
    

    Update 2:

    It now works with jQuery on Node.js too. So you have the option of doing either client-side or server-side parsing with the same library.

    Update 3:

    Since the Google Code shutdown, jquery-csv has been migrated to GitHub.

    Disclaimer: I am also the author of jQuery-CSV.

    0 讨论(0)
  • 2020-11-21 08:32

    I'm not sure why I couldn't get Kirtan's example to work for me. It seemed to be failing on empty fields or maybe fields with trailing commas...

    This one seems to handle both.

    I did not write the parser code, just a wrapper around the parser function to make this work for a file. See attribution.

        var Strings = {
            /**
             * Wrapped CSV line parser
             * @param s      String delimited CSV string
             * @param sep    Separator override
             * @attribution: http://www.greywyvern.com/?post=258 (comments closed on blog :( )
             */
            parseCSV : function(s,sep) {
                // http://stackoverflow.com/questions/1155678/javascript-string-newline-character
                var universalNewline = /\r\n|\r|\n/g;
                var a = s.split(universalNewline);
                for(var i in a){
                    for (var f = a[i].split(sep = sep || ","), x = f.length - 1, tl; x >= 0; x--) {
                        if (f[x].replace(/"\s+$/, '"').charAt(f[x].length - 1) == '"') {
                            if ((tl = f[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
                                f[x] = f[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
                              } else if (x) {
                            f.splice(x - 1, 2, [f[x - 1], f[x]].join(sep));
                          } else f = f.shift().split(sep).concat(f);
                        } else f[x].replace(/""/g, '"');
                      } a[i] = f;
            }
            return a;
            }
        }
    
    0 讨论(0)
  • 2020-11-21 08:35

    Here's my simple vanilla JavaScript code:

    let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
    console.log(splitQuotes(a))
    
    function splitQuotes(line) {
      if(line.indexOf('"') < 0) 
        return line.split(',')
    
      let result = [], cell = '', quote = false;
      for(let i = 0; i < line.length; i++) {
        char = line[i]
        if(char == '"' && line[i+1] == '"') {
          cell += char
          i++
        } else if(char == '"') {
          quote = !quote;
        } else if(!quote && char == ',') {
          result.push(cell)
          cell = ''
        } else {
          cell += char
        }
        if ( i == line.length-1 && cell) {
          result.push(cell)
        }
      }
      return result
    }
    
    0 讨论(0)
  • 2020-11-21 08:36

    Just use .split(','):

    var str = "How are you doing today?";
    var n = str.split(" ");
    
    0 讨论(0)
  • 2020-11-21 08:37

    I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.

        //
        //
        // CSV to object
        //
        //
    
        const new_line_char = '\n';
        const field_separator_char = ',';
    
        function parse_csv(csv_str) {
    
            var result = [];
    
            let line_end_index_moved = false;
            let line_start_index = 0;
            let line_end_index = 0;
            let csr_index = 0;
            let cursor_val = csv_str[csr_index];
            let found_new_line_char = get_new_line_char(csv_str);
            let in_quote = false;
    
            // Handle \r\n
            if (found_new_line_char == '\r\n') {
                csv_str = csv_str.split(found_new_line_char).join(new_line_char);
            }
            // Handle the last character is not \n
            if (csv_str[csv_str.length - 1] !== new_line_char) {
                csv_str += new_line_char;
            }
    
            while (csr_index < csv_str.length) {
                if (cursor_val === '"') {
                    in_quote = !in_quote;
                } else if (cursor_val === new_line_char) {
                    if (in_quote === false) {
                        if (line_end_index_moved && (line_start_index <= line_end_index)) {
                            result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
                            line_start_index = csr_index + 1;
                        } // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
                    } // Else: just ignore because we are in a quote
                }
                csr_index++;
                cursor_val = csv_str[csr_index];
                line_end_index = csr_index;
                line_end_index_moved = true;
            }
    
            // Handle \r\n
            if (found_new_line_char == '\r\n') {
                let new_result = [];
                let curr_row;
                for (var i = 0; i < result.length; i++) {
                    curr_row = [];
                    for (var j = 0; j < result[i].length; j++) {
                        curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
                    }
                    new_result.push(curr_row);
                }
                result = new_result;
            }
            return result;
        }
    
        function parse_csv_line(csv_line_str) {
    
            var result = [];
    
            //let field_end_index_moved = false;
            let field_start_index = 0;
            let field_end_index = 0;
            let csr_index = 0;
            let cursor_val = csv_line_str[csr_index];
            let in_quote = false;
    
            // Pretend that the last char is the separator_char to complete the loop
            csv_line_str += field_separator_char;
    
            while (csr_index < csv_line_str.length) {
                if (cursor_val === '"') {
                    in_quote = !in_quote;
                } else if (cursor_val === field_separator_char) {
                    if (in_quote === false) {
                        if (field_start_index <= field_end_index) {
                            result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
                            field_start_index = csr_index + 1;
                        } // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
                    } // Else: just ignore because we are in quote
                }
                csr_index++;
                cursor_val = csv_line_str[csr_index];
                field_end_index = csr_index;
                field_end_index_moved = true;
            }
            return result;
        }
    
        function parse_csv_field(csv_field_str) {
            with_quote = (csv_field_str[0] === '"');
    
            if (with_quote) {
                csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
                csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
            }
            return csv_field_str;
        }
    
        // Initial method: check the first newline character only
        function get_new_line_char(csv_str) {
            if (csv_str.indexOf('\r\n') > -1) {
                return '\r\n';
            } else {
                return '\n'
            }
        }
    
    0 讨论(0)
提交回复
热议问题