Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a CSV file into Javascript array has one of the keys in quotes

Tags:

javascript

I am trying to parse a CSV file into a Javascript array but have run into a an issue which I am a little stumped.

Though the rest of the objects are parsed without a quote for the key, one of the Keys is in quotes but when I try Object[key] I get an exception

Uncaught SyntaxError: Invalid or unexpected token

I am able to read all other keys except for "information".

My object looks like this:

Object {LGA_NAME: "DANDENONG", Lat: "-37.98862", Long: "145.21805", "Information
": "something crashed
"}

The CSV file in question is

https://dl.dropboxusercontent.com/u/97162408/crashdata.csv

The function which I use to parse the CSV file is

    function csvToArray(csvString) {

        // The array we're going to build
        var csvArray = [];
        // Break it into rows to start
        var csvRows = csvString.split(/\n/);

        // Take off the first line to get the headers, then split that into an array
        var csvHeaders = csvRows.shift().split(',');

        // Loop through remaining rows
        for (var rowIndex = 0; rowIndex < csvRows.length; ++rowIndex) {
            var rowArray = csvRows[rowIndex].split(',');

            // Create a new row object to store our data.
            var rowObject = csvArray[rowIndex] = {};

            // Then iterate through the remaining properties and use the headers as keys
            for (var propIndex = 0; propIndex < rowArray.length; ++propIndex) {
                // Grab the value from the row array we're looping through...
                var propValue = rowArray[propIndex];
                // ...also grab the relevant header (the RegExp in both of these removes quotes)
                var propLabel = csvHeaders[propIndex];

                rowObject[propLabel] = propValue;
            }
        }
        return csvArray;
    }
like image 810
Navyseal Avatar asked Jun 08 '16 02:06

Navyseal


1 Answers

The problem is in the way you split the string to get the lines. In *NIX systems, lines are broken with \n, but in Windows lines are broken with \r\n. Because the CSV file is following the Windows convention and you split the lines using just \n, the last key is actually "Information\r".

You can fix this issue by replacing var csvRows = csvString.split(/\n/); with var csvRows = csvString.split(/\n|\r\n/); this way you are going to be able to parse CSV files that use either line break conventions.

like image 61
Rodrigo5244 Avatar answered Oct 23 '22 21:10

Rodrigo5244