This JavaScript coding example demonstrates a method to parse a Comma Separated Values (CSV) file.
The project was split up for teaching purposes.
The actions are:
- Determine what character separates the column values (comma, tab or blank)
- What are the column names from line one, if any do not look like a column name, then generate them and use line 1
- Ignore blank lines, and skip leading blanks in a column value
- Added a row number column for validation purposes (this is a teaching app)
- Return an array of column values for each row until the end of the file
- Display an HTML table of the CSV file
|
The source code is divided into four sections:
csv_test.js | The program to test the CSV parser
|
csv_object.js | This object places tokens into an array of column values.
The function "nextRecord" returns false at the end of the file
|
csv_parse_object.js | This object splits the file into tokens, one for each column value.
The function "nextToken" returns "true" for each column value, and return "false" at the end of the record
|
csv_token_object.js | This object holds a column value, internal use only
|
The two main support routines are:
csv_object$defineColumns | The function scans the first line of the file to determine the number of columns and their names.
All column names can only use characters A-Z,a-z,0-9, if not then it is assumed to be un-named and the columns names are generated
|
csv_parse_object$defineSeparator | This function scans the first line to determine the column separator.
It looks for a TAB(09), Comma(,) or Blank(32). This is done by scanning each character upto a Line Feed (10), ignoring any character inside of single or double quotes, and storing all others.
The stored characters are checked first for a Comma, then a Tab, then a Blank. If none are found, then a Comma is set as the column separator
|