【问题标题】:First property inaccsesible of objects parsed by csv-parse由 csv-parse 解析的对象的第一个属性不可访问
【发布时间】:2021-05-29 19:43:58
【问题描述】:

我正在使用 csv-parse 解析具有以下内容的 csv 文件 -

userID,sysID
20,50
30,71

但是,在返回的对象上,无法访问从第一列 userID 创建的属性。

这是我的代码--


async function main(){
    let systemIDs = await getSystemIds('./systems.csv');     
    console.log(`Scanning data for ${systemIDs.length} systems..`);

    console.log(systemIDs[0]);
    console.log(systemIDs[0].userID); // This prints undefined 
    console.log(systemIDs[0].sysID);  // This prints the correct value
}

async function getSystemIds(path){
    let ids= [];
    await new Promise ((resolve,reject)=>{        
        const csvParser = csvParse({columns:true, skip_empty_lines: true});
        FS.createReadStream(path)
        .pipe(csvParser)
        .on('readable', ()=>{
            let record ;            
            while(record = csvParser.read()) {
                ids.push(record);
            }            
        })
        .on('finish',()=>{
            resolve();
        });
    });
    return ids;
}

输出 -

Scanning data for 2 systems..
{ 'userID': '20', sysID: '50' } 
undefined  // <== The Problem
50

我注意到第一列键 userID 在控制台输出中有单引号,而 sysID 没有。但不知道是什么原因造成的。

【问题讨论】:

  • csv文件中能有空格吗?
  • 另外,你能在 console.log(record) 之后:while(record = csvParser.read()) {
  • @Skarlinski 看起来一样 { 'userID': '20', sysID: '50' }
  • 听起来像是原始 csv 中一些奇怪的 unicode 或隐藏空格问题
  • 我会测试其他 csv,或者在使用 inspect 运行时添加断点。

标签: javascript node.js csv-parse


【解决方案1】:

最后自己想通了……

我需要 BOM 选项。 documentation 声明它应该为 UTF-8 文件设置为 true。但它默认为 false。

Excel 默认生成 csv 文件,其中 BOM 作为 CSV 文件中的第一个字符。这被解析器作为标题(和键名)的一部分拾取。 将 bom 选项设置为 true,它可以处理从 excel 或其他程序生成的 csv 文件。

const csvParser = csvParse({
  columns: true, 
  skip_empty_lines: true,
  bom: true
});

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 2018-02-25
    • 2010-11-02
    • 1970-01-01
    • 2011-09-11
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多