raosa
raosa

Reputation: 129

JSON to CSV/Excel in Nodejs

I am trying to convert the JSON:

Results: 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"}]]

to something a .csv file or excel file and download

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

Could someone provide a snippet of the js code that will help to implement this?

What I tried:

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

This just prints in the console as :

"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"

Upvotes: 0

Views: 1227

Answers (1)

Adem
Adem

Reputation: 61

Download csv-parser npm pack.

npm i -s csv-parser

And for download;

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

Basic tutorial for run at js page;

// (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!");

Upvotes: 0

Related Questions