0

我尝试使用 csvtojson

const csv = require("csvtojson");
const csvFilePath = require('./../../books.csv');
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
})

我的 file.csv 是

Book,Author,Amount,Price
The Compound Effect,Darren Hardy,5,9.48
The 7 Habits of Highly Effective People,Stephen R. Covey,4,23.48
The Miracle Morning,Hal Elrod,10,21.34
Influence: The Psychology of Persuasion,Robert B. Cialdini,4,12.99
The ONE Thing,Gary Keller,1,11.18

我有下一个错误

The Compound Effect,Darren Hardy,5,9.48
^^^^^^^^

SyntaxError: Unexpected identifier
 at Module._compile (internal/modules/cjs/loader.js:723:23)

怎么了?谢谢)

4

3 回答 3

1

这里的问题是您正在使用该功能require('./../../books.csv');来导入文件。

阅读文档后,我可以保证您只需将路径传递给 CSV 文件。

所以,你的代码应该是这样的:

const csv = require('csvtojson');
const csvFilePath = './../../books.csv';

csv().fromFile(csvFilePath).then((jsonObj)=>{
    console.log(jsonObj);
})

所需的输出应该是:

[ { Book: 'The Compound Effect',
    Author: 'Darren Hardy',
    Amount: '5',
    Price: '9.48' },
  { Book: 'The 7 Habits of Highly Effective People',
    Author: 'Stephen R. Covey',
    Amount: '4',
    Price: '23.48' },
  { Book: 'The Miracle Morning',
    Author: 'Hal Elrod',
    Amount: '10',
    Price: '21.34' },
  { Book: 'Influence: The Psychology of Persuasion',
    Author: 'Robert B. Cialdini',
    Amount: '4',
    Price: '12.99' },
  { Book: 'The ONE Thing',
    Author: 'Gary Keller',
    Amount: '1',
    Price: '11.18' } ]
于 2019-11-19T23:30:20.467 回答
1

通过更改路径解决了问题)

const csvFilePath = './../../books.csv';

const csvFilePath = `${__dirname}/../../books.csv`;

但是,我认为在这种情况下使用 '__dirname' 并不是一个好主意。如果您对此有任何想法,请写出来)

于 2019-11-20T08:04:09.383 回答
0

我认为您应该"在 .csv 文件中包含或quote用于处理选项

https://www.npmjs.com/package/csvtojson#parameters

于 2019-11-19T22:50:49.957 回答