首页 > 解决方案 > Parsing CSV content with Javascript

问题描述

I searched and tried many solutions including papa parser in angular and functions offered in the related Stackoverflow question...no luck. I always have a problem with fields which contain comma.

CSV file structure is like this: (export from Numbers)

name; address
Jack; 762 Texas Rd, Morganville NJ 07751 USA

...but I know that ";" or "," would have been a possible delimiter.

In papa, I tried to set delimiter '', so I expect papa parser to find the delimiter itself.

this.papa.parse(csv_content,{
      delimiter: '',
      complete: (result) => {
        if(result != undefined){
          console.log('Parsed: ', result);
        }
      }
    });

...It didn't papa parsed using ',' and not ';'. It couldn't detect ; as the delimiter.

If I convert all semi columns (;) into commas (,) and try to parse, than address field is splitted.

What is your suggestion?

标签: javascriptcsv

解决方案


明确设置分隔符,而不是将其留给自动检测。

const csv_content = `name; address
Jack; 762 Texas Rd, Morganville NJ 07751 USA`;

Papa.parse(csv_content, {
  delimiter: ';',
  complete: (result) => {
    if (result != undefined) {
      console.log('Parsed: ', JSON.stringify(result.data, null, 2));
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.6.2/papaparse.min.js"></script>


推荐阅读