Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get the column headers? #436

Open
Thomas-1985 opened this issue Aug 11, 2024 · 3 comments
Open

How to get the column headers? #436

Thomas-1985 opened this issue Aug 11, 2024 · 3 comments

Comments

@Thomas-1985
Copy link

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
Copy link
Member

wdavidw commented Aug 12, 2024

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

@Thomas-1985
Copy link
Author

Thomas-1985 commented Aug 19, 2024

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
Copy link
Member

wdavidw commented Aug 20, 2024

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: ";" }
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants