1

I'm uploading and then reading the CSV file but I'm facing an issue while splitting it, so basically, column names in CSV contain ',' so when I'm going to split the columns with ',' so I don't get the full column value, please suggest me some proper way for it. Thanks

const readCsv = (file) => {
    const reader = new FileReader();
    const filetext = reader.readAsBinaryString(file);
    reader.addEventListener('load', function (e) {
        const data = e.target.result;
        let parsedata = [];

        let newLinebrk = data.split('\n');
        for (let i = 0; i < newLinebrk.length; i++) {
            parsedata.push(newLinebrk[i].split(','));
        }
        console.log("parsedData: ", parsedata);
    });
};

CSV:

column 1   column2                    
test       lorem, ipsum, dummy/text

after splitting:

['test', 'lorem', 'ipsum', 'dummy/text']

so by doing that I'm unable to get a proper column name that contains a comma in string.

Zain Khan
  • 1,644
  • 5
  • 31
  • 67
  • May I know if exploring existing solutions, such as [csv-reader](https://www.npmjs.com/package/csv-reader), can be considered? Also, is it okay to consider changing the delimiter to some other character (may be ^ or ~) instead of comma? – jsN00b Jan 21 '22 at 12:45
  • 1
    @jsN00b don't wanna use any 3rd party library – Zain Khan Jan 21 '22 at 12:47
  • Issue is that within the code, how does one differentiate which comma is the delimiter (indicating end of a column) and which comma is part of the cell (text)? – jsN00b Jan 21 '22 at 12:49
  • yes, that is my question :) – Zain Khan Jan 21 '22 at 12:50
  • @jsN00b can you share an example in react with csv-reader? – Zain Khan Jan 21 '22 at 12:57
  • [LMGTFY](https://lmgtfy.app/?q=csv-reader+reactjs+example+codesandbox) and, [here is one example](https://codesandbox.io/s/react-csv-reader-vtull) – jsN00b Jan 21 '22 at 13:03
  • @jsN00b this is also doing the same, splits my original column value – Zain Khan Jan 21 '22 at 13:08
  • You need to check for values between quotes. In any case, this question has been answered here: https://stackoverflow.com/questions/1293147/example-javascript-code-to-parse-csv-data – Michael Beeson Jan 21 '22 at 13:21

1 Answers1

1

In my case, I used Papa Parse which fulfills my all requirements.

const readCsv = (file) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.addEventListener('load', function (e) {
        const data = e.target.result;
        Papaparse.parse(data, {
            complete: function (results) {
                console.log("results: ", results.data);
            },
        });
    });
};
Zain Khan
  • 1,644
  • 5
  • 31
  • 67