¿Cómo analizar datos CSV?

Resuelto Pierre-Gilles Levallois asked hace 15 años • 15 respuestas

¿Dónde puedo encontrar código JavaScript para analizar datos CSV?

Pierre-Gilles Levallois avatar Aug 18 '09 17:08 Pierre-Gilles Levallois
Aceptado

Puede utilizar la función CSVToArray() mencionada en esta entrada de blog.

      console.log(CSVToArray(`"foo, the column",bar
2,3
"4, the value",5`));

      // ref: http://stackoverflow.com/a/1293163/2343
        // This will parse a delimited string into an array of
        // arrays. The default delimiter is the comma, but this
        // can be overriden in the second argument.
        function CSVToArray( strData, strDelimiter ){
            // Check to see if the delimiter is defined. If not,
            // then default to comma.
            strDelimiter = (strDelimiter || ",");
     
            // Create a regular expression to parse the CSV values.
            var objPattern = new RegExp(
                (
                    // Delimiters.
                    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
     
                    // Quoted fields.
                    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
     
                    // Standard fields.
                    "([^\"\\" + strDelimiter + "\\r\\n]*))"
                ),
                "gi"
                );
     
     
            // Create an array to hold our data. Give the array
            // a default empty first row.
            var arrData = [[]];
     
            // Create an array to hold our individual pattern
            // matching groups.
            var arrMatches = null;
     
     
            // Keep looping over the regular expression matches
            // until we can no longer find a match.
            while (arrMatches = objPattern.exec( strData )){
     
                // Get the delimiter that was found.
                var strMatchedDelimiter = arrMatches[ 1 ];
     
                // Check to see if the given delimiter has a length
                // (is not the start of string) and if it matches
                // field delimiter. If id does not, then we know
                // that this delimiter is a row delimiter.
                if (
                    strMatchedDelimiter.length &&
                    strMatchedDelimiter !== strDelimiter
                    ){
     
                    // Since we have reached a new row of data,
                    // add an empty row to our data array.
                    arrData.push( [] );
     
                }
     
                var strMatchedValue;
     
                // Now that we have our delimiter out of the way,
                // let's check to see which kind of value we
                // captured (quoted or unquoted).
                if (arrMatches[ 2 ]){
     
                    // We found a quoted value. When we capture
                    // this value, unescape any double quotes.
                    strMatchedValue = arrMatches[ 2 ].replace(
                        new RegExp( "\"\"", "g" ),
                        "\""
                        );
     
                } else {
     
                    // We found a non-quoted value.
                    strMatchedValue = arrMatches[ 3 ];
     
                }
     
     
                // Now that we have our value string, let's add
                // it to the data array.
                arrData[ arrData.length - 1 ].push( strMatchedValue );
            }
     
            // Return the parsed data.
            return( arrData );
        }
Expandir fragmento

Kirtan avatar Aug 18 '2009 10:08 Kirtan

jQuery-CSV

Es un complemento jQuery diseñado para funcionar como una solución de un extremo a otro para analizar CSV en datos JavaScript. Maneja todos los casos extremos presentados en RFC 4180 , así como algunos que aparecen para exportaciones de hojas de cálculo de Excel/Google (es decir, que en su mayoría involucran valores nulos) en los que falta la especificación.

Ejemplo:

pista,artista,álbum,año

Peligroso, 'Busta Rhymes', 'Cuando ocurre un desastre', 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'

Actualizar:

Ah, sí, probablemente también debería mencionar que es completamente configurable.

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

Actualización 2:

Ahora también funciona con jQuery en Node.js. Por lo tanto, tiene la opción de realizar un análisis del lado del cliente o del servidor con la misma biblioteca.

Actualización 3:

Desde el cierre de Google Code, jquery-csv se ha migrado a GitHub .

Descargo de responsabilidad: también soy el autor de jQuery-CSV.

Evan Plaice avatar Apr 24 '2012 01:04 Evan Plaice