Parsing JSON file to csv

836 Views Asked by At

I am trying to parse JSON file to csv. I've found a json2csv library and it works beside the fact that it expects the json file to be arranged in this way:

[
{
column: value,
column2: value2 
},
{
column: value3,
column2: value4 
}
]

While my layout for JSON file (that comes from linguiJS for translations) looks like this:

{
 value1 :{
column2: value2,
column3: value3,
}
}

So it returns a file formatted horizontally, like this: enter image description here

Converter js:

const converter = require('json-2-csv');
const fs = require('fs');

const file = JSON.parse(fs.readFileSync('./locale/fr/messages.json'));

converter.json2csv(file, (err, csv) => {
    if (err) {
        throw err;
    }

    console.log(csv)

    fs.writeFileSync('./localisation.csv', csv);
});

What's the easiest way to solve this for a very beginner?

1

There are 1 best solutions below

0
Raphael Pr On

You should probably do something like:

// ...
const file = JSON.parse(fs.readFileSync('./locale/fr/messages.json'));

const formattedFile = Object.entries(file).map((key, values) => {
  // You can defined your desired format here ->
  return { 'messageId': key, ...values }
})

converter.json2csv(formattedFile, (err, csv) => {
// ...