In my recent post about JSON Table Editor, I listed reading CSV under feature to-do list. Working on it, I remember that I have blogged about reading CSV in the past.
So I ported the code from C# to JavaScript. The porting process is very much painless since C# and JavaScript has the same dialect. The JavaScript implementation is much simpler compared to C# because JavaScript is a dynamic language. You can compare the code side by side if you think I bluffed you :D.
Please understand that I wrote the C# implementation way back when I was only have Visual Studio 2005 in my workstation. So sadly, no anonymous object for me that time.
You could argue why complicated method is being used instead of just splitting the string using comma, but simple splitting won’t work when the CSV contains comma inside brackets.
Anyway, enjoy the code and have fun coding.
Cheers!
var CsvDataSource = { cleanQuotes : function (raw) { //Remove extra quotes/spaces in the beginning and end of string //Parse the string into Boolean or Number var str = raw; while (str.charAt(0) == '"' && str.charAt(str.length - 1) == '"') str = str.substr(1, str.length - 2); if (str.trim) str = str.trim(); if (str == "true") return true; else if (str == "false") return false; else if (Number(str)) return Number(str); else return str; }, csvSplits : function (data, separatorChar) { //Split a string using the specified separator character. Will keep value between quotes //as a single value var me = CsvDataSource; var result = []; var lastpost = 0; var insideQuote = false; for (var i = 0; i < data.length; i++) { if (data.charAt(i) == separatorChar) { if (!insideQuote) { var str = me.cleanQuotes(data.substr(lastpost, i - lastpost)); result.push(str); lastpost = i + 1; } if (i > 0 && i < data.length - 1) { if (data.charAt(i - 1) == '"' && insideQuote) { var str = me.cleanQuotes(data.substr(lastpost, i - lastpost)); result.push(str); lastpost = i + 1; insideQuote = false; } if (data.charAt(i + 1) == '"' && !insideQuote) insideQuote = true; } } } result.push(me.cleanQuotes(data.substr(lastpost))); return result; }, readCSV : function (rawText, separatorChar) { var result = []; var lines = rawText.split('\n'); for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (Ext.String.trim(line) != '') { var values = this.csvSplits(line, separatorChar); result.push(values); } } return result; } }
Update 8th Feb 2013
- Removed the opening and closing quotes in CSV values
- Try to convert the String value into Boolean or Number, if failed, remains as a String
loading...
About Hardono
Incoming Search
csv, data, javascript