这样做的方法之一是:
// based on json_parse from JavaScript The Good Part by D. Crockford
var csv_parse = function () {
var at,
ch,
text,
error = function (m) {
throw {
name: SyntaxError ,
message: m,
at: at,
text: text
};
},
next = function (c) {
if (c && c !== ch) {
error("Expected " + c + " instead of " + ch + " ");
}
ch = text.charAt(at);
at += 1;
return ch;
},
//needed to handle "" which indicates escaped quote
peek = function () {
return text.charAt(at);
},
white = function () {
while (ch && ch <= && ch !==
) {
next();
}
},
// if numeric, then return number
number = function () {
var number,
string = word();
number = +string;
if (isNaN(number)) {
return string;
} else {
return number;
}
},
word = function () {
var string = ;
while (ch !== , && ch !==
) {
string += ch;
next();
}
return string;
},
// the matching " is the end of word not ,
// need to worry about "", which is escaped quote
quoted = function () {
var string = ;
if (ch === " ) {
while (next()) {
if (ch === " ) {
//print( need to know ending quote or escaped quote );
// need to know ending quote or escaped quote ("")
if (peek() === " ) {
//print( maybe double quote near +string);
next( " );
string += ch;
} else {
next( " )
return string;
}
} else {
string += ch;
}
}
return string;
}
error("Bad string");
},
value = function () {
white();
switch(ch) {
case - :
return number();
case " :
return quoted();
default:
return ch >= 0 && ch <= 9 ? number() : word();
}
return number();
},
line = function () {
var array = [];
white();
if (ch ===
) {
next(
);
return array;//empty []
}
while (ch) {
array.push( value() );
white();
if (ch ===
) {
next(
);
return array;//got something
}
next( , );// not very liberal with delimiter
white();
}
};
return function (_line) {
var result;
text = _line;
at = 0;
ch = ;
result = line();
white();
if (ch) {
error("Syntax error");
}
return result;
};
}();