简体   繁体   English

在字段中处理带有换行符的 csv 文件 - node.js

[英]processing csv files with line breaks in fields - node.js

Im trying to process a csv file with line breaks (\\n) inside the fields.我正在尝试处理字段内带有换行符 (\\n) 的 csv 文件。 Each field is enclosed in double quotes.每个字段都用双引号括起来。 Is there any node.js package that can handle this type of csv?有没有可以处理这种类型的 csv 的 node.js 包?

I tried parsing it with readline in node.我尝试在 node.js 中使用 readline 解析它。 It detects the lines as seperate records even though they are in the same field.即使它们在同一字段中,它也会将这些行检测为单独的记录。

csv can handle rows containing line breaks: csv可以处理包含换行符的行:

'use strict'

let csv = require('csv');

let str = `id;name;desc
"1";"name1";"desc
on multiple
line"
"2";"name2";"desc2"`;

csv.parse(str,
    {
        delimiter: ';', // default is ,
        columns: true,  // if the first of the csv line is headers
    },
    (err, data) => {
        if (err) console.log(err);
        console.log(JSON.stringify(data, null, 3));
    });

/* output:
[
   {
      "id": "1",
      "name": "name1",
      "desc": "desc\non multiple\nline"
   },
   {
      "id": "2",
      "name": "name2",
      "desc": "desc2"
   }
]
*/

/* without column: true
[
   [
      "id",
      "name",
      "desc"
   ],
   [
      "1",
      "name1",
      "desc\non multiple\nline"
   ],
   [
      "2",
      "name2",
      "desc2"
   ]
]
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM