4

I am working with the csv-parse module in npm to download a CSV file over Ajax. I want to read it into an array of objects.

Here is the CSV file that I'm working with:

val,row_id,date,row_name
19378.02,10Q,2013-10-01,NHS Oxfordshire
14104.81,01M,2014-01-01,NHS North Manchester
11130.65,09D,2014-09-01,NHS Brighton & Hove
3611.32,08J,2014-11-01,NHS Kingston

And here is my code:

    $.ajax({
      type: "GET",
      url: _this.globalOptions.numeratorUrl,
      error: function() {
       // show error
      },
      success: function(data) {
        parse(data,
             {columns: ['val','row_id','date','row_name'] },
             function(err, output){
                console.log('parsed', output);
             }
        );
      }

This works, but there are two things I would like to improve:

  • By default it includes the header row, so output[0] looks like this: { 'val': 'val', 'row_id': 'row_id', ...}. Is there some way I can automatically skip the header row?
  • I don't like the fact that I have to define columns explicitly in order to produce an array of objects. The name and the ordering of the columns may vary. Is there some way I can automatically use the values from the header row, whatever they are?

1 Answer 1

3

from the documentation, by link given:

columns (array|boolean|function) List of fields as an array, a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, default to null, affect the result data set in the sense that records will be objects instead of arrays.

and that is an answer, so

$.ajax({
  type: "GET",
  url: _this.globalOptions.numeratorUrl,
  error: function() {
   // show error
  },
  success: function(data) {
    parse(data,
         {columns: true },
         function(err, output){
            console.log('parsed', output);
         }
    );
  }
Sign up to request clarification or add additional context in comments.

2 Comments

That works! Thank you, I just found the phrasing of the documentation confusing.
If you use custom column names, use option fromLine: 2 to skip first line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.