1

I want to convert a json array of elements to csv in node.js. I've found some module doing that like json2csv or json-csv but they are not complete. For example json2csv only support a flat structure where fields are direct children of the json root and also the schema should be the same for all json objects.
In my case, I want that.
I suppose that i've a json array of objects like that:

[{
    "libelle" : "Projet 1",
    "beneficiaire" : "Mr Leroy",
    "nature" : "Diagnostics patrimoniaux",
    "phasage" : "GLOBAL",
    "budget": [
        {"status": "BROUILLON"}
    ],
    "status" : "BROUILLON"
},
{
    "libelle" : "Projet 2",
    "beneficiaire" : "Mr Leroy",
    "nature" : "Diagnostics patrimoniaux",
    "phasage" : "GLOBAL",
    "status" : "BROUILLON"
}]

and i want to convert it to csv like that:

"libelle","beneficiaire","nature","phasage","budget[0].status","status"
"Projet 1","Mr Leroy","Diagnostics patrimoniaux","GLOBAL","BROUILLON","BROUILLON"
"Projet 2","Mr Leroy","Diagnostics patrimoniaux","GLOBAL",,"BROUILLON"

I'm looking for a good and complete node module for doing that. If it doesn't exist, I will do it myself i think so.

4
  • stackoverflow.com/questions/16831250/… Look at this ling may help you Commented Jan 7, 2015 at 10:48
  • 1
    I've seen that and it's not what i want. Your link convert csv to json and me i want the reverse operation. Commented Jan 7, 2015 at 10:55
  • Can you use PHP for this ? Commented Jan 7, 2015 at 10:58
  • No I can't just node (javascript) Commented Jan 7, 2015 at 11:13

2 Answers 2

5

You can use the module jsonexport its pretty easy, check this sample:

Sample:

var jsonexport = require('jsonexport');

var contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
});

The ouput:

lastname;name;family.type;family.name;nickname;location
Smith;Bob;Father;Peter;;
David;James;Mother;Julie;;
Miller;Robert;;;;1231,3214,4214
Martin;David;;;dmartin;

Source: https://www.npmjs.com/package/jsonexport

Sign up to request clarification or add additional context in comments.

1 Comment

Can it be used in TypeScript environment?
0

Yes, there are a few npm modules, like fast-csv and ya-csv, that are very helpful for this.

var csv = require('ya-csv');
var fastcsv = require('fast-csv');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.