How to get the data from my file with "json2csv" of Node.js module

691 Views Asked by At

I'm trying to convert json file to CSV format. In the example https://www.npmjs.com/package/json2csv

const { parse } = require('json2csv');

const fields = ['field1', 'field2', 'field3'];
const opts = { fields };

try {
  const csv = parse(myData, opts);
  console.log(csv);
} catch (err) {
  console.error(err);
}

I don't understand what to do with myData, I tried that:

    const { parse } = require('json2csv');
const mydata = require("./mydata.json");



const fields = ['id', 'name'];
const opts = { fields };

try {
  const csv = parse(mydata , opts);
  console.log(csv);
} catch (err) {
  console.error(err);
}

But I don't see the value of mydata, I only get the value which is id and name.

I think it's not going to the child level, which I can see the data

1

There are 1 best solutions below

1
Gron465 On

mydata was in this form:

{
    "something": value,
    "something2": [
        {
            "id": 1,
            "name": "name"
        }
    ]
}

I had to remove and make it like that:

[
        {
            "id": 1,
            "name": "name"
        }
    ]

That's a solution but I didn't want to change "mydata" file, if anyone have another solution, thank you.