Skip to content

Instantly share code, notes, and snippets.

@johanbove
Last active August 29, 2015 14:22
Show Gist options
  • Save johanbove/88b1154cd67c4c5cb50d to your computer and use it in GitHub Desktop.
Save johanbove/88b1154cd67c4c5cb50d to your computer and use it in GitHub Desktop.
Parsing text file to JS loaded through ajax request
// @see http://www.amcharts.com/tutorials/loading-external-data/
/*
2011-02-23,133034
2011-02-24,122290
2011-02-25,383603
2011-02-28,125285
2011-03-01,118042
2011-03-02,102500
2011-03-03,434047
2011-03-04,422374
2011-03-07,396473
2011-03-08,453142
*/
function loadCSV (file) {
var request;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
request = new XMLHttpRequest();
} else {
// code for IE6, IE5
request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
function parseCSV (data) {
//replace UNIX new lines
data = data.replace (/\r\n/g, "\n");
//replace MAC new lines
data = data.replace (/\r/g, "\n");
//split into rows
var rows = data.split("\n");
var chartData = [];
// loop through all rows
for (var i = 0, len = rows.length; i < len; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
// column is array now
// first item is date
var date = column[0];
// second item is value of the second column
var value = column[1];
// create object which contains all these items:
var dataObject = {
date: date,
visits: value
};
// add object to chartData array
chartData.push(dataObject);
}
}
return chartData;
}
var data = loadCSV("data.txt");
parseCSV(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment