4

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!

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

And then? What should I do to write it into multiple columns in a csv file?
do, you mean all tab delimited? I adjusted my example to use tabs.
What module do you use? I use the node-csv-parser module, but the tab doesn't work.
Oh! I got it! It's the difference between operating systems. The csv file displays one column in ubuntu, and displays multiple columns in windows.
0

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.

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.