2

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?

ewef
  • 57
  • 8
  • 1
    Does this answer your question? [Convert CSV data into JSON format using Javascript](https://stackoverflow.com/questions/27979002/convert-csv-data-into-json-format-using-javascript) – esqew Mar 29 '21 at 23:17
  • @esqew Thank you for your help. However, that is not what I am working on. I am converting a csv String to Json. The link you sent is related to converting a csv File to Json. – ewef Mar 29 '21 at 23:21
  • What output were you expecting instead? – CertainPerformance Mar 29 '21 at 23:27
  • @CertainPerformance Based on the example, the headers in the result are looking like ```"name,", "age," and "booktitle,"```. As you can see, the csv headers contain the commas at the end. However, I am expecting the output without commas, looking like ```"name", "age" and "booktitle" ``` – ewef Mar 29 '21 at 23:32
  • Yeah, definitely, I didn't see the trailing commas. But `,""Alas, What Can I do?""` seems like the format is wrong - why two quotes? `,"Alas, What Can I do?"` would make much more sense..? – CertainPerformance Mar 29 '21 at 23:40
  • @CertainPerformance Thank you for your comment. I am only focusing on the header which is ```name, age and book title```. – ewef Mar 29 '21 at 23:48
  • If you just want to parse those headers, then just split by a comma (or match non-quotes inside of quotes) – CertainPerformance Mar 29 '21 at 23:50

1 Answers1

1

Looks like your problem is the attribute names from your current solution. They sometimes have "," in the end.

If that is the case, the simplest solution is just to remove them using the replace method.

console.log( "something,".replace( ",", "" ) )
console.log( "age".replace( ",", "" ) )
Thiago Mata
  • 2,825
  • 33
  • 32