0

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?

5
  • It would help a little bit more if you provide a more precise example in your input JSON. Using the same value/column in your input and output would help to understand what you need. It seems to me that you are only manipulating JSON files, therefore doing it outside of reactjs / react-native would allow you to use dedicated tool like jq for instance. If you are doing inside an app -> please provide some javascript context. Commented Sep 2, 2020 at 9:59
  • Thank's for a reply - i've added a simple converter code that i am currently using to parse and convert data. Commented Sep 2, 2020 at 10:15
  • stackoverflow.com/a/31536517/3237884 , this answer could be helpful Commented Sep 2, 2020 at 10:21
  • json2csv works because it expects a specific layout, or rather, it expects an array of objects. What you posted is a single object with a single object property that in turn has two simple properties. How do you expect that to appear in a file? As a single flattened row? What happens to value1 then, is it discarded? Commented Sep 2, 2020 at 10:23
  • BTW json2csv seems to support flattening nested objects already. Commented Sep 2, 2020 at 10:25

1 Answer 1

1

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) => {
// ...

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.