Skip to content

Parsing with columns: true, cast: true throws for csv data that has numeric column headers #477

@chriswheeldon

Description

@chriswheeldon

Describe the bug

Parsing with columns: true, cast: true throws for csv data that has numeric column headers.

The following error is, for example, thrown in parse:

CsvError Error: Invalid column definition: expect a string or a literal object, got 2023 at position 1

I think ideally columns: true, cast: true would not attempt to cast header row elements and instead preserve them as strings. I'd be happy to contribute a fix if that makes sense as a solution!

Note, adding from: 2 does not workaround the issue. The only workaround I could find was to implement a cast function like,

cast: (value, context) => {
  if (context.header) {
    return value;
  }
  const casted = Number(value);
  return isNaN(casted) ? value : casted;
},

I am using csv version 6.4.1.

To Reproduce

import dedent from "dedent";

// Dataset with numeric header elements and numeric values
const data = dedent`
  Person,2023,2024,2025
  John,100,150,200`;

const parsed = parse(data, {
  columns: true,
  cast: true,
}); // THROWS

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions