Project Description
Agnes is a mature javascript framework for parsing CSV.


Agnes is comprised of three simple, well tested functions.

function purpose
csvToJson Convert csv into an array of json objects.
jsonToCsv Convert a json object (or json array) into csv.
rowDelimiter Detect the line separator used by the current browser


function: csvToJson

Converts a piece of separated text into an array of Json objects. Assumes the first row of the csv is the name of the properties to create (i.e. assumes the csv includes a row of column headers).

var csvData, jsonData;
csvData = "Name,Age\nJack,12\nJohn,5";
jsonData = agnes.csvToJson(csvData);
alert(JSON.stringify(jsonData)); 


Returns:

{ [Name":"Jack","Age":"12,Name":"John","Age":"5] }

function: jsonToCsv

Converts a json object (or array of json objects) into a separated string. You can optionally provide the row delimiter, field delimiter and qualifying character. If you omit these parameters, sensible defaults are assumed.

var jsonData, csvData;
jsonData = [{ "name" : "Mary" }, { "name" : "Alice" }];
csvData = agnes.jsonToCsv(jsonData);
alert(csvData); 


...returns


name
Mary
Alice


var jsonData, csvData;
jsonData = [{ "name" : "fred", "age" : 22}];
csvData = agnes.jsonToCsv(jsonData, "\r\n", "|", '"');
alert(csvData); 


...returns

name|age
fred|22


function: rowDelimiter

Determines the standard line ending used on your current browser. Does your current browser use just a carriage return? Or does it use a carriage return plus a line feed?

Note that Agnes does not use old school 'agent' investigation, but the more mature approach of 'feature detection' -- making sure she doesn't get tricked into a wrong answer.

var delim = agnes.rowDelimiter();
// in order to show you the invisible characters
// in the result, i now need to escape it...
delim = delim.replace("\r","\\r");
delim = delim.replace("\n","\\n");
delim = delim.replace("\t","\\t");
alert("the standard line separator on this browser seems to be... " + delim);


...returns

the standard line separator on this browser seems to be... \n

(or whatever it happens to be...)

Last edited Oct 22, 2011 at 2:51 PM by secretGeek, version 4