I am trying to convert a csv string to json in javascript.
I referred to the following link first answer: "What Is The Best Way To Convert From Csv To Json When Commas And Quotations May.
However, when I try that, the header contains a comma so I am not able to render a data Table.
const csvToJson = (str, headerList, quotechar = '"', delimiter = ',') => {
const cutlast = (_, i, a) => i < a.length - 1;
// const regex = /(?:[\t ]?)+("+)?(.*?)\1(?:[\t ]?)+(?:,|$)/gm; // no variable chars
const regex = new RegExp(`(?:[\\t ]?)+(${quotechar}+)?(.*?)\\1(?:[\\t ]?)+(?:${delimiter}|$)`, 'gm');
const lines = str.split('\n');
const headers = headerList || lines.splice(0, 1)[0].match(regex).filter(cutlast);
const list = [];
for (const line of lines) {
const val = {};
for (const [i, m] of [...line.matchAll(regex)].filter(cutlast).entries()) {
// Attempt to convert to Number if possible, also use null if blank
val[headers[i]] = (m[2].length > 0) ? Number(m[2]) || m[2] : null;
}
list.push(val);
}
return list;
}
const testString = `name,age,booktitle
John,,Hello World
Mary,3,""Alas, What Can I do?""
Joseph,5,"Waiting, waiting, waiting"
"Donaldson Jones" , six, "Hello, friend!"`;
console.log(csvToJson(testString));
console.log(csvToJson(testString, ['foo', 'bar', 'baz']));
I have also tried to figure out RegExp written but could not understand it.
Can anybody tell me how to remove a comma from that answer or a better suggestion?