繁体   English   中英

使用 Javascript 和节点 csv-parse 将 csv 文件解析为数组

[英]using Javascript and node csv-parse to parse csv file into an array

我有一个项目,我必须处理输入 CSV 文件并将其存储到我可以添加到的数组中,然后将其打印到 CSV 文件中。 然后,我使用我项目的 rest 的事务数据,因此能够完成这部分至关重要,因为将使用其他 CSV 文件执行测试。

我的问题是,在使用 csv-parse 时,如果我使用 console.table(results); 当我在命令终端中运行 .js 文件时,它显示了 csv 对象,所以我知道它的解析,但无论我做什么,我都无法将 go 的对象放入我的数组变量中。

控制台.table(结果);

请有人给我一个关于我哪里出错的提示:

var fs = require('fs');
var parse = require('csv-parse');


var transactionValues = []; //Need an array to hold transactions

//constuctor for transactions
function addData (id, accountType, initiatorType, dateTime, transactions) {
  var data = {
    "AccountID" : id,
    "AccountType" : accountType,
    "InitiatorType" : initiatorType,
    "DateTime" : dateTime,
    "TransactionValues" : transactions
  }
  transactionValues.push(data); //should add a new line
}

    var parser = parse({columns: true}, function (err, results) {
console.table(results);
addData(results.index[0].AccountID, results.index[0].AccountType, results.index[0].InitiatorType, results.index[0].DateTime, results.index[0].TransactionValue, 0);
}); //attempted to save the objects into the array but no success

fs.createReadStream(__dirname+'/testData/customer-1234567-ledger.csv').pipe(parser)

console.log(transactionValues); // array is empty

我相信results已经是一个正常的数组,因为它是从 csv-parse 返回的。 您正在尝试使用results.index[0]访问第一个元素,但它只是results[0] 另一个问题是fs.createReadStream(...).pipe(...)是异步的。 这意味着您的console.log将在完成解析之前运行。 您需要将解析后必须运行的任何代码放入parse function 的回调中。 像这样的东西:

var parser = parse({columns: true}, function (err, results) {
  console.table(results);
  for (const row of results) { //loop through each object parsed from the csv
    addData(row.AccountID, row.AccountType, row.InitiatorType, row.DateTime, row.TransactionValue, 0);
  }
  console.log(transactionValues); // this should be populated properly

  /* Do anything that needs to use transactionValues here */
});

暂无
暂无

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

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