Reputation: 51
Now I have several JSON in my mongodb, such as:
{
title: "title_1",
content: "content_1",
author: "author_1"
}
And I want to write these data into a csv file with the format below:
title content author
title_1 content_1 author_1
title_2 content_2 author_2
...
I used the node-csv-parser module. But it always write in only the first column in the csv file, such as:
title content author
title_1,content_1,author_1
title_1,content_1,author_2
...
What should I do to achieve my aim? Please show me some examples. Any help would be greatly appreciated!
Upvotes: 4
Views: 3193
Reputation: 17319
convert to nested arrays, join.
var array = [
{
title: "title_1",
content: "content_1",
author: "author_1"
},
{
title: "title_1",
content: "content_1",
author: "author_2"
}
];
var keys = Object.keys(array[0]);
var csv = [keys.join('\t')];
array.forEach(function (data) {
var row = [];
keys.forEach(function (key) {
row.push(data[key]);
});
csv.push(row.join('\t'));
});
csv = csv.join('\n');
output:
title content author
title_1 content_1 author_1
title_1 content_1 author_2
Upvotes: 5
Reputation: 3263
please refer below link to generate your json or csv vice-versa
http://www.cparker15.com/code/utilities/csv-to-json/
I hope this will be useful to you.
Thanks.
Upvotes: 0