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.
asked Jan 21, 2022 at 12:40
Zain Khan
1,8946 gold badges45 silver badges78 bronze badges
-
May I know if exploring existing solutions, such as 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– jsN00b2022年01月21日 12:45:22 +00:00Commented Jan 21, 2022 at 12:45
-
1@jsN00b don't wanna use any 3rd party libraryZain Khan– Zain Khan2022年01月21日 12:47:12 +00:00Commented Jan 21, 2022 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– jsN00b2022年01月21日 12:49:00 +00:00Commented Jan 21, 2022 at 12:49
-
yes, that is my question :)Zain Khan– Zain Khan2022年01月21日 12:50:01 +00:00Commented Jan 21, 2022 at 12:50
-
@jsN00b can you share an example in react with csv-reader?Zain Khan– Zain Khan2022年01月21日 12:57:19 +00:00Commented Jan 21, 2022 at 12:57
1 Answer 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);
},
});
});
};
answered Jan 21, 2022 at 13:33
Zain Khan
1,8946 gold badges45 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js