开发者

Best method of getting Javascript data from a simple 3-row CSV

I have a simple CSV (imported using JQuery's $.ajax from the /data/league.csv on the same site) with three lines in this exact format:

"Kimberlin Library","Queen's Building","Innovation Centre","etc etc"
8,2,0,-2
1,0,-1,0

which I'd like to get into this format (to use building and percent as data for the x-y axes in Highcharts, and also to populate a list with all three):

var leaguetable = {
    building: ["Kimberlin Library","Queen's Building","开发者_运维问答Innovation Centre","etc etc"],
    percent: [8,2,0,-2],
    change: [1,0,-1,0]
};

embarrassingly trivial, but I keep drawing a blank, despite trying other people's methods (including split(/\r\n|\n|r/), searching for /^(.*)$/m), and this question), so prepared to start from scratch. I need something as simple as possible, either JQuery or pure Javascript. For a similar problem I ended up converting the file to JSON, but I'd like to avoid that if possible.


Try this. It will handle simple CSV, and single- or double-quoted CSV, all via the regex pattern in the code below. You'll have to adjust the end of processCSV() to do what you want, since I'm just returning the object into thin air.

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "my_csv.txt",
        dataType: "text",
        success: function(data) {processCSV(data);}
     });
 });

function processCSV(allLines) {
    var allLinesArray = allLines.split(/\r\n|\n/);
    var leaguetable = { 'building': [], 'percent': [], 'change': [] };
    var pattern = /([^,'"]*"[^"]*"[^,'"]*)|([^,'"]*'[^']*'[^,'"]*)|([^,"']*)/ig;
    var fieldValues;

    for (var i=0; i<allLinesArray.length; i++) {
        fieldValues = allLinesArray[i].match(pattern);
        if (fieldValues) {
            for (var j=0; j<fieldValues.length; j++) {
                // if begins with single- or double-quote, strip specified quotes
                if (fieldValues[j].charAt(0) === '"' || fieldValues[j].charAt(0) === "'") {
                    fieldValues[j] = fieldValues[j].replace(fieldValues[j].substr(0,1), "");
                }
            }
            // I'll trust your CSV to have the right number of fields, but...
            // you may want to build some validation in before doing the next 3 lines
            leaguetable.building.push(fieldValues[1]);
            leaguetable.percent.push(fieldValues[2]);
            leaguetable.change.push(fieldValues[3]);
        }
    }
    return leaguetable;
}


Assuming your CSV is simple, you'll probably want to do something like this:

  1. Split the data into lines.
  2. Iterate over the lines:
    1. Split the line on a comma.
    2. Append the first part to the building array.
    3. Append the second part to the percent array, after parsing it with parseInt.
    4. Do the same for the third part and the change array.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜