Code Javascript pour analyser les données CSV [dupliquer]

cette question a déjà une réponse ici:

  • Comment puis-je analyser une chaîne CSV avec Javascript, qui contient une virgule dans les données? 13 Réponses

est-ce que quelqu'un a une idée d'où je pourrais trouver du code javascript pour analyser les données CSV ?

187
demandé sur Evan Plaice 2009-08-18 14:54:37

8 réponses

vous pouvez utiliser la fonction CSVToArray () mentionnée dans cette entrée de blog.

<script type="text/javascript">
    // 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 );
    }

</script>
229
répondu Kirtan 2014-06-16 15:20:41

je pense que je peux suffisamment battre Kirtan la réponse de

Enter jQuery-CSV

c'est un plugin jquery conçu pour fonctionner comme une solution de bout en bout pour analyser CSV dans les données Javascript. Il traite chaque cas de bord unique présenté dans RFC 4180 , ainsi que certains qui apparaissent pour les exportations Excel/Google Spreadsheed (c'est-à-dire principalement impliquant des valeurs nulles) que la spécification a disparu.

exemple:

de la piste,artiste,album,année

Dangereux "De Busta Rhymes','En Cas De Catastrophe',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'

mise à jour:

Oh oui, je devrais aussi mentionner que c'est complètement configurable.

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

mise à Jour 2:

il fonctionne maintenant avec jQuery sur noeud.js aussi. Vous avez donc la possibilité de faire le parsing côté client ou côté serveur avec la même lib.

mise à Jour 3:

depuis Google Code shutdown, jQuery-csv a été migré vers GitHub .

Avertissement: je suis aussi l'auteur de jQuery-CSV.

143
répondu Evan Plaice 2017-05-23 11:55:05

j'ai un mise en œuvre dans le cadre d'un projet de feuille de calcul.

ce code n'est pas encore testé en profondeur, mais tout le monde est invité à l'utiliser.

comme certaines des réponses ont noté cependant, votre mise en œuvre peut être beaucoup plus simple si vous avez réellement DSV ou TSV fichier, car ils interdisent l'utilisation de l'enregistrement et des séparateurs de champ dans les valeurs. CSV, sur l'autre main peut il y a en fait des virgules et des lignes à l'intérieur d'un champ, ce qui casse la plupart des approches regex et split-based.

var CSV = {
parse: function(csv, reviver) {
    reviver = reviver || function(r, c, v) { return v; };
    var chars = csv.split(''), c = 0, cc = chars.length, start, end, table = [], row;
    while (c < cc) {
        table.push(row = []);
        while (c < cc && '\r' !== chars[c] && '\n' !== chars[c]) {
            start = end = c;
            if ('"' === chars[c]){
                start = end = ++c;
                while (c < cc) {
                    if ('"' === chars[c]) {
                        if ('"' !== chars[c+1]) { break; }
                        else { chars[++c] = ''; } // unescape ""
                    }
                    end = ++c;
                }
                if ('"' === chars[c]) { ++c; }
                while (c < cc && '\r' !== chars[c] && '\n' !== chars[c] && ',' !== chars[c]) { ++c; }
            } else {
                while (c < cc && '\r' !== chars[c] && '\n' !== chars[c] && ',' !== chars[c]) { end = ++c; }
            }
            row.push(reviver(table.length-1, row.length, chars.slice(start, end).join('')));
            if (',' === chars[c]) { ++c; }
        }
        if ('\r' === chars[c]) { ++c; }
        if ('\n' === chars[c]) { ++c; }
    }
    return table;
},

stringify: function(table, replacer) {
    replacer = replacer || function(r, c, v) { return v; };
    var csv = '', c, cc, r, rr = table.length, cell;
    for (r = 0; r < rr; ++r) {
        if (r) { csv += '\r\n'; }
        for (c = 0, cc = table[r].length; c < cc; ++c) {
            if (c) { csv += ','; }
            cell = replacer(r, c, table[r][c]);
            if (/[,\r\n"]/.test(cell)) { cell = '"' + cell.replace(/"/g, '""') + '"'; }
            csv += (cell || 0 === cell) ? cell : '';
        }
    }
    return csv;
}
};
36
répondu Andy VanWagoner 2012-10-08 16:20:16

voici un analyseur CSV extrêmement simple qui traite les champs Cités avec des virgules, de nouvelles lignes, et a échappé aux guillemets doubles. Il n'y a pas de séparation ou de RegEx. De l'analyse de la chaîne d'entrée 1-2 caractères à la fois, et construit un tableau.

tester à http://jsfiddle.net/vHKYH / .

function parseCSV(str) {
    var arr = [];
    var quote = false;  // true means we're inside a quoted field

    // iterate over each character, keep track of current row and column (of the returned array)
    for (var row = col = c = 0; c < str.length; c++) {
        var cc = str[c], nc = str[c+1];        // current character, next character
        arr[row] = arr[row] || [];             // create a new row if necessary
        arr[row][col] = arr[row][col] || '';   // create a new column (start with empty string) if necessary

        // If the current character is a quotation mark, and we're inside a
        // quoted field, and the next character is also a quotation mark,
        // add a quotation mark to the current column and skip the next character
        if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; }  

        // If it's just one quotation mark, begin/end quoted field
        if (cc == '"') { quote = !quote; continue; }

        // If it's a comma and we're not in a quoted field, move on to the next column
        if (cc == ',' && !quote) { ++col; continue; }

        // If it's a newline (CRLF) and we're not in a quoted field, skip the next character
        // and move on to the next row and move to column 0 of that new row
        if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; }

        // If it's a newline (LF or CR) and we're not in a quoted field,
        // move on to the next row and move to column 0 of that new row
        if (cc == '\n' && !quote) { ++row; col = 0; continue; }
        if (cc == '\r' && !quote) { ++row; col = 0; continue; }

        // Otherwise, append the current character to the current column
        arr[row][col] += cc;
    }
    return arr;
}
19
répondu Trevor Dixon 2017-10-20 12:35:22

Voici mon PEG(.js) grammaire qui semble bien fonctionner à la RFC 4180 (c.-à-d. qu'elle traite les exemples à 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 '"'; }
  / [^"]

essayez à http://jsfiddle.net/knvzk/10 ou http://pegjs.majda.cz/online . Télécharger l'analyseur généré à https://gist.github.com/3362830 .

14
répondu Trevor Dixon 2012-08-15 19:36:26

csvToArray v1.3

une fonction compacte (645 octets) mais conforme pour convertir une chaîne CSV en tableau 2D, conforme à la norme RFC4180.

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

usage commun: jQuery

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

usage commun: Javascript

csvAsArray = csvAsString.csvToArray();

Remplacer le séparateur de champ

csvAsArray = csvAsString.csvToArray("|");

Outrepasser le séparateur d'enregistrement

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

Ignorer Ignorer L'En-Tête

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

Remplacer tout

csvAsArray = csvAsString.csvToArray("|", "#", 1);
13
répondu dt192 2018-04-04 09:26:35

Je ne sais pas pourquoi je ne pouvais pas kirtans ex. à travailler pour moi. Il semblait échouer sur des champs vides ou peut-être des champs avec des virgules à l'arrière...

celui-ci semble s'occuper des deux.

Je n'ai pas écrit le code de l'analyseur, juste un wrapper autour de la fonction d'analyseur pour que cela fonctionne pour un fichier. voir 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) {
            // /q/javascript-string-newline-character-65894/","), 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;
        }
    }
3
répondu Shanimal 2012-01-19 20:38:32

pourquoi ne pas l'utiliser.split (',')?

http://www.w3schools.com/jsref/jsref_split.asp

var str="How are you doing today?";
var n=str.split(" "); 
-3
répondu Micah 2012-09-17 21:17:52