0

我正在尝试转换 JSON:

结果:console.log(( ${JSON.stringify(results)});


[
[{"field":"StudentID","value":"A"},{"field":"Total Marks","value":"27853"}],[{"field":"StudentID","value":"B"},{"field":"Total Marks","value":"14337"}],[{"field":"StudentID","value":"C"},{"field":"Total Marks","value":"1324"}],[{"field":"StudentID","value":"D"},{"field":"Total Marks","value":"362"}],[{"field":"StudentID","value":"E"},{"field":"Total Marks","value":"209"}]]

到 .csv 文件或 excel 文件并下载

Student ID  Total Marks
A           27853
B           14337
C           1324
D           362
E           209

有人可以提供一个有助于实现这一点的 js 代码片段吗?

我尝试了什么:

const json2csvParser = new Parser();
            results.forEach(element => {
                const csv = json2csvParser.parse(element);
                console.log(csv);
            });
            const csv = json2csvParser.parse(results);
            console.log(csv);

这只是在控制台中打印为:

"field","value"
"Student ID","A"
"Total Marks","27853"
"field","value"
"Student ID","B"
"Total Marks","14337"
"field","value"
"Student ID","C"
"Total Marks","1324"
"field","value"
"Student ID","D"
"Total Marks","362"
"field","value"
"Student ID","E"
"Total Marks","209"
4

1 回答 1

0

下载 csv-parser npm 包。

npm i -s csv-parser

并供下载;

const fs = require("fs");
fs.writeFileSync("demo.csv", csv);
console.log("Done!");

js页面运行基础教程;

// (A) DATA ARRAY
var data = [
    ["Alpha", "Beta"],
    ["Charlie", "Delta"],
    ["Echo", "Foxtrot"]
  ];
  
  // (B) WRITE TO FILE
  const fs = require("fs");
  const stream = fs.createWriteStream("demoC.csv");
  for (let i of data) { stream.write(i.join(",") + "\r\n"); }
  stream.end();
  console.log("Done!");
于 2022-01-31T22:31:59.700 回答