adaltas / node-csv

Full featured CSV parser with simple api and tested against large datasets.
https://csv.js.org
MIT License
3.98k stars 263 forks source link

How to get the column headers? #436

Open Thomas-1985 opened 1 month ago

Thomas-1985 commented 1 month ago

Describe the bug

Version: 5.5.3

I am using the sync api to parse a csv file and get the records. I also need the headers (on the first line) for later analysis but they are not present in the records (maybe thats intentional). How do i get these?

To Reproduce

I am using the following code for parsing

const data = file.data;
    const parseResult = parse(data, {
      cast: true,
      columns: true,
      skip_empty_lines: true,
      trim: true,
      info: true,
      delimiter
    } as Options);
wdavidw commented 1 month ago

Please edit your sample, it is expected to contain the data input string as well as the expected result.

Thomas-1985 commented 3 weeks ago

input:

articles.csv:

name,description,price
Image 1;First image;100
Image 2;Second image;200
Image 3;Third image;50

expected output:

{
    "records": [
        {
            "name": "Image 1",
            "description": "First image",
            "price": "100"
        },
        {
            "name": "Image 2",
            "description": "Second image",
            "price": "200"
        },
        {
            "name": "Image 3",
            "description": "Third image",
            "price": "500"
        }
    ]
}

and the column headers from the first line
['name','description','price']
wdavidw commented 3 weeks ago

Using the column option returns objects, instead of arrays, whose keys represent the header field. You could use Object.keys(records[0]) but , according to your expected output above, it does not seem to fill your expectations.

I assume the header line shall be separated by ; instead of , since the issue is not about parsing different kind of separators.

From my understanding, you could just extract the first line and interpret it as headers, see the "436.js" example:

const [headers, ...records] = parse(
  dedent`
  name;description;price
  Image 1;First image;100
  Image 2;Second image;200
  Image 3;Third image;50
  `,
  { delimiter: ";" }
);