Saturday, 6 May 2017

How to save in a csv file so that every attribute is in a new column using "json2csv"

So I use "Json2csv" and I tried an example:

   var fs = require('fs'); 
   var json2csv = require('json2csv');
   var fields = ['car', 'price', 'color'];
   var fieldNames = ['Car Name', 'Price USD','Color'];
   var myCars = [
        {
           "car": "Audi",
           "price": 40000,
            "color": "blue"
        }, {
            "car": "BMW",
            "price": 35000,
            "color": "black"
        }, {
            "car": "Porsche",
            "price": 60000,
            "color": "green"
        }
    ];

    var opts = {
        data: myCars,
        fields: fields,
        fieldNames: fieldNames,
        quotes: ';'
    };
    var csv = json2csv(opts);



    fs.writeFile('file2.csv', csv, function (err) {
        if (err) throw err;
        console.log('file saved');
    });

I get this :

enter image description here

But I want something like this:

enter image description here

As you can see it always creates for each "," a new column, but I just want for each attribute as you can see in the second picture.



via KeyNavas

No comments:

Post a Comment