1

I'm new to node js. I'm trying to create a .csv file but I think something is wrong in my code;

const Json2csvParser = require('json2csv').Parser;

let fields = ["key1", "key2", "key3", "key4", "key5", "key6", "key7"]

let retval = {
    key1: ["a", "b", "c"],
    key2: ["a", "b", "c"],
    key3: ["a", "b", "c"],
    key4: ["a", "b", "c"],
    key5: ["a", "b", "c"],
    key6: ["a", "b", "c"],
    key7: ["a", "b", "c"]
};

const json2csvParser = new Json2csvParser({ fields });
const result = json2csvParser.parse(retval);

console.log(result);
fs.writeFile("localPath/test.csv", [result], "utf8", function (err) {
    if (err) {
        console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
        console.log('It\'s saved!');
    }
});

I wanna get this result:

key1 key2 key3 key4 key5 key6 key7
 a    a     a    a   a   a   a
 b    b     b    b   b   b   b
 c    c     c    c   c   c   c

but I got this;

"key1","key2","key3","key4","key5","key6","key7"
"[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]","[""a"",""b"",""c""]"

Where did I go wrong?

1 Answer 1

3

retval should be a list of rows :

[
  // row 1
  {
    key1: "a",
    key2: "a",
    key3: "a",
    key4: "a",
    key5: "a",
    key6: "a",
    key7: "a"
  },
  // row 2
  {
    key1: "b",
    key2: "b",
    key3: "b",
    key4: "b",
    key5: "b",
    key6: "b",
    key7: "b"
  }
  // more rows
];

see https://www.npmjs.com/package/json2csv#example-1

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

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.