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!
01.
var
CsvDataSource = {
02.
cleanQuotes :
function
(raw) {
03.
//Remove extra quotes/spaces in the beginning and end of string
04.
//Parse the string into Boolean or Number
05.
var
str = raw;
06.
while
(str.charAt(0) ==
'"'
&& str.charAt(str.length - 1) ==
'"'
)
07.
str = str.substr(1, str.length - 2);
08.
09.
if
(str.trim)
10.
str = str.trim();
11.
12.
if
(str ==
"true"
)
13.
return
true
;
14.
else
if
(str ==
"false"
)
15.
return
false
;
16.
else
if
(Number(str))
17.
return
Number(str);
18.
else
19.
return
str;
20.
},
21.
csvSplits :
function
(data, separatorChar) {
22.
//Split a string using the specified separator character. Will keep value between quotes
23.
//as a single value
24.
var
me = CsvDataSource;
25.
var
result = [];
26.
var
lastpost = 0;
27.
var
insideQuote =
false
;
28.
for
(
var
i = 0; i < data.length; i++) {
29.
if
(data.charAt(i) == separatorChar) {
30.
if
(!insideQuote) {
31.
var
str = me.cleanQuotes(data.substr(lastpost, i - lastpost));
32.
33.
result.push(str);
34.
lastpost = i + 1;
35.
}
36.
37.
if
(i > 0 && i < data.length - 1) {
38.
if
(data.charAt(i - 1) ==
'"'
&& insideQuote) {
39.
var
str = me.cleanQuotes(data.substr(lastpost, i - lastpost));
40.
result.push(str);
41.
lastpost = i + 1;
42.
insideQuote =
false
;
43.
}
44.
if
(data.charAt(i + 1) ==
'"'
&& !insideQuote)
45.
insideQuote =
true
;
46.
}
47.
}
48.
}
49.
result.push(me.cleanQuotes(data.substr(lastpost)));
50.
return
result;
51.
},
52.
readCSV :
function
(rawText, separatorChar) {
53.
var
result = [];
54.
var
lines = rawText.split(
'\n'
);
55.
for
(
var
i = 0; i < lines.length; i++) {
56.
var
line = lines[i];
57.
if
(Ext.String.trim(line) !=
''
) {
58.
var
values =
this
.csvSplits(line, separatorChar);
59.
result.push(values);
60.
}
61.
}
62.
return
result;
63.
}
64.
}
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