-2

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

Gron465
  • 25
  • 1
  • 9
  • This resembles your question. You may answer there: https://stackoverflow.com/questions/44313296/json2csv-not-outputting-values. Hope you take it positively, downvoting this question – devilpreet Feb 15 '22 at 09:45

1 Answers1

0

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.

Gron465
  • 25
  • 1
  • 9
  • 1
    Answering own questions is acceptable, as long as they provide concrete problem and information. Refer existing high rated Q&A. Edit this to include input file in question. For answer you need to add why input fails. Since this is json to csv, default parsing wont handle complex input. Then this problem and solution might help others. – devilpreet Feb 15 '22 at 09:42