CSV Reader

Joshua Paine <[email protected]> Tue, 29 Apr 2008 17:37:59 -0400
Newsgroups gmane.comp.java.helma.general
Message-ID <1209505079.27866.6.camel@Lenny>
--=-pjts7yEFRW4cGGGK8CLZ
Content-Type: text/plain
Content-Transfer-Encoding: 7bit

I needed a CSV reader, so I made one using the Apache-licensed opencsv
from <http://opencsv.sourceforge.net/>. I can't recall if attachments
make it through to this list, but I'm giving it a try. This is
undocumented, but it's only 40 lines and should be quite obvious.

It can return lines as arrays or as hashmaps (JavaScript Object) with
the column headings used as the keys. The only thing that might not be
obvious is that for the latter style you have to call getHeaders()
before trying to read anything.

-- 
Joshua Paine

--=-pjts7yEFRW4cGGGK8CLZ
Content-Disposition: attachment; filename=CSVReader.js
Content-Type: application/javascript; name=CSVReader.js
Content-Transfer-Encoding: 7bit

var CSVReader = function(file,sep,quote,start) {
	sep || (sep = ',');
	quote || (quote = '"');
	start || (start = 0);
	var reader = new Packages.au.com.bytecode.opencsv.CSVReader(new java.io.FileReader(file),sep,quote,start);
	var headers = [], pub, linesRead = 0;
	return pub = {
		getHeaders: function() {
			if(headers.length) return headers;
			else if(linesRead) return null;
			(headers = reader.readNext()) && (headers = Array.prototype.slice.call(headers,0)) && linesRead++;
			return headers;
		},
		nextList: function() {
			var list = reader.readNext();
			if(list) (list = Array.prototype.slice.call(list,0)), linesRead++;
			else pub.close();
			return list;
		},
		nextMap: function() {
			var list = pub.nextList();
			var map = {};
			if(!list) return list;
			for(var i = 0; i<list.length && i<headers.length; i++) map[headers[i]] = list[i];
			return map; 
		},
		allList: function() {
			var out = [], line;
			while(line = pub.nextList()) out.push(line);
			return out;
		},
		allMap: function() {
			var out = [], line;
			while(line = pub.nextMap()) out.push(line);
			return out;
		},
		close: function(){
			return reader.close();
		}
	}
}

--=-pjts7yEFRW4cGGGK8CLZ
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

_______________________________________________
Helma-user mailing list
[email protected]
http://helma.org/mailman/listinfo/helma-user

--=-pjts7yEFRW4cGGGK8CLZ--