CSV.js
CSV.js copied to clipboard
The last column without header does not seem to be parsed
Hi, i found a case that when the last column does not have a header, it can not be parsed.
The codes look like this
const data = "user_id,name\r\n1234,xxx,extra\r\n";
console.log(new CSV(data).parse());
// =>
[
[user_id, name],
[1234, xxx],
]
Actually i want to get a result like this
[
[user_id, name, ''],
[1234,xxx,extra],
]
Besides, i found that if there is a comma at the end of the header, the last column can be parsed, but there seem to be some other problems
const data = "user_id,name,\r\n1234,xxx,extra\r\n";
console.log(new CSV(data).parse());
// =>
[
[user_id, name,0],
[1234, xxx,NaN],
]
https://codesandbox.io/s/determined-bell-4bb6r?file=/src/App.js
Is there any way to solve it?
The CSV parser uses the header as a schema.
If the first row has 6 columns, it assumes every row has 6 columns.
For your use case, I would recommend manually passing in the cast option and either passing in a CSV with no header or with the correct header.
new CSV(data, {cast: [“Number”, “String”, “String”]})
Thanks for your reply!
Actually the csv file is upload by someone else, i do not know the header until the file is being uploaded. I have to verify the file using some rules, such as each column whose cells are not all empty should have a header.
Maybe i have to manually make some comparisons between the first row and the others.