How to convert JSON to CSV and then save to computer as CSV file

3.8k Views Asked by At

I'm currently trying to pull json data from and API, convert it to csv using the json2csv node.js module, and then save the data as a csv file on my laptop. However, when I run the script, nothing happens.

The json data is then formatted similar to the below data variable:

const apiDataPull = postDataRequest()
   .then(data => {
      data = [
         {
            'day': '*date*',
            'revenue': '*revenue value*'
         }
      ]

And this is to convert the data to csv and download it, which is where the problem seems to be arising:

apiDataPull.then(data => {

   json2csv({
      data: data,
      fields: ['day', 'revenue', 'totalImpressions', 'eCPM']
   },
   function(err, csv) {
      if (err) console.log(err);
      fs.writeFile('pubmaticData.csv', csv, function(err){
         if (err) throw err;
         console.log('File Saved!')
      });
   });

});

There is data being pulled from the API, but it's not being saved. I'm not even sure if it's been converted to csv properly or not.

2

There are 2 best solutions below

0
On BEST ANSWER

You are probably not starting the promises, and it looks like you are not using the json2csv correctly.

Take a look at this example:

let json2csv = require("json2csv");
let fs = require("fs");

apiDataPull = Promise.resolve([
    {
        'day': '*date*',
        'revenue': '*revenue value*'
    }]).then(data => {
    return json2csv.parseAsync(data, {fields: ['day', 'revenue', 'totalImpressions', 'eCPM']})
}).then(csv => {
    fs.writeFile('pubmaticData.csv', csv, function (err) {
        if (err) throw err;
        console.log('File Saved!')
    });
});

The saved file is:

"day","revenue","totalImpressions","eCPM"
"*date*","*revenue value*",,
0
On

You can use this npm package - csv-stringify. https://github.com/adaltas/node-csv-stringify

//Load HTTP module
const http = require("http");
var stringify = require('csv-stringify');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
//Create HTTP server and listen on port 3000 for requests
const server = http.createServer(async (req, res) => {        
stringify(jsonObject, {header:true}, function(err, output) {
        fs.writeFile('formatted_json.csv', output, 'utf8', function(err) {
            if (err) {
                console.log('Some error occured - file either not saved or corrupted file saved.');
            } else {
                console.log('It\'s saved!');
            }
        });
    });

});

//listen for request on port 3000, and as a callback function have the port listened on logged
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

This should help you. Create this file - name it index.js Make sure you have node & npm installed, and run in the same directory

npm install
npm install csv-stringify
node index.js

go to your browser open localhost:3000 and you will see formatted_json.csv created in the same directory where index.js is located. Hope this helps!