Tuesday, February 22, 2011

Working with CSV files using AS3: Part 2

Today we load data from a CSV file into flash using AS3 and parse it into an array of arrays.

Firstly, we need to create the URLRequest object and specify the path to our csv file:

var myRequest:URLRequest = new URLRequest("example.csv");

Next, we create the main array which will be used for storing loaded data:

var loadedData:Array = [];

Then we create an URLLoader object, add an Event.COMPLETE event and feed it the path to our file.

var myLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onload);
myLoader.load(myRequest);

Now we can trace the full file data:

function onload(Event):void
{
trace("Full file:");
trace(myLoader.data);
}

The output window will show us this:

Full file:
ID,First name,Last name,Job

1,John,Goodman,Driver

2,Henry,Williams,Pharmacist

3,Jimmy,Orange,Godfather

4,Mary,Thompson,Nurse

5,Derrick,Jackson,Police man

6,Clint,Eastwood,Cowboy

Now, lets put each row into its own array. To do that, we split the data by /\r\n|\n|\r/, which is a RegExp pattern that works with CSV files that can be created on all platforms (Windows puts \r\n between variables, Mac puts \r and Linux puts \n).

loadedData = myLoader.data.split(/\r\n|\n|\r/);
trace("First line:");
trace(loadedData[0]);

We traced the first line of the CSV:

First line:
ID,First name,Last name,Job

Now we want to have each value separately, so we split each row by comma:

for (var i:int=0; i<loadedData.length; i++){
loadedData[i] = loadedData[i].split(",");
}

We will now be able to refer to the values like this:

trace("Second line, second value:");
trace(loadedData[1][1]);

Output:

Second line, second value:
John

And that's how you do it.

Here's the full code:

var myRequest:URLRequest = new URLRequest("example.csv");
var loadedData:Array = [];
var myLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onload);
myLoader.load(myRequest);

function onload(Event):void
{
trace("Full file:");
trace(myLoader.data);

loadedData = myLoader.data.split(/\r\n|\n|\r/);
trace("First line:");
trace(loadedData[0]);

for (var i:int=0; i<loadedData.length; i++){
loadedData[i] = loadedData[i].split(",");
}

trace("Second line, second value:");
trace(loadedData[1][1]);
}

Thanks for reading!

Related:

Working with CSV files using AS3: Part 1
Working with CSV files using AS3: Part 3
Working with CSV files using AS3: Part 4
Working with CSV files using AS3: Part 5

1 comment:

oddshocks said...

Cool. Useful post, thanks.

Post a Comment