我有一个 CSV 文件,其中包含 3 个文件,如附图所示:
我正在运行时下载它并尝试使用 NodeJS 将其转换为 JSON 格式。
我期望的 JSON 格式结果是:
[
[
"PO_NO",
"PO_LINE_ID",
"MAT_ID",
],
{
"PO_NO": "2044344",
"PO_LINE_ID": "1",
"MAT_ID": "XZZ04152-100-994"
},
{
"PO_NO": "2044344",
"PO_LINE_ID": "1",
"MAT_ID": "XZZ04152-100-992"
}
]
但实际上我得到了这个,因此我可以使用我的 JSON 数据:
[
[
"sep=;"
],
{
"sep=;": "PO_NO;PO_LINE_ID;MAT_ID"
},
{
"sep=;": "2044344;1;XZZ04152-100-994"
},
{
sep=;": "2044344;2;XZZ04152-100-992"
}
]
如何避免它并将其转换为正确的 JSON 格式?
这是我用来将 csv 转换为 Json 的 Nodejs/Javascript 代码
const csvFilePath = 'cypress/logger/Dataset.csv'; // Path to the CSV file
const fs = require('fs');
const csv = require('csv-parser');
const results = [];
fs.createReadStream(csvFilePath)
.pipe(csv())
.on('headers', (headers) => {
results.push(headers); // Add headers as the first element in the results array
})
.on('data', (data) => {
results.push(data);
})
.on('end', () => {
const jsonData = JSON.stringify(results);
fs.writeFile('cypress/logger/Datasetfile1.json', jsonData, (err) => {
if (err) {
console.error('Error writing JSON file:', err);
} else {
console.log('CSV to JSON conversion completed.');
}
});
});
注意:我想强调的一件重要的事情如果我在 Visual Studio 代码中打开 CSV 文件,它会有额外的 sep=;导致问题的行。
sep=;
PO_NO;PO_LINE_ID;MAT_ID;
0002044344;1;XZZ04152-100-994;
0002044344;2;XZZ04152-100-992;
0002044344;3;XZZ04152-997-992;
如果标头被处理为1个大标头, 那么你需要定义分隔符
.pipe(csv({ separator: ';' }))