mrodrig / json-2-csv

Convert JSON to CSV *or* CSV to JSON!
https://mrodrig.github.io/json-2-csv
MIT License
420 stars 58 forks source link

Problem with list of objects same keys #207

Closed mebibou closed 8 months ago

mebibou commented 3 years ago

Background Information

The issue I'm reporting is with:

I have...

When doing the following:

json2csv([{
  list: [{
    a: 1
  }, {
    a: 2
  }]
}], {
  expandArrayObjects: true
})

The current resulting csv is:

list.a
[1,2]

which looks like you had instead:

[{
  list: [{
    a: [1, 2]
  }]
}]

But the CSV could actually reflect the original structure if it was like this instead:

list.0.a,list.1.a
1,2

I understand some might want the first result, but it would be nice to have an option to have a more like-to-like representation?

mrodrig commented 2 years ago

Thanks for reporting this @mebibou. I can definitely see this as being useful as well, especially if converting back to JSON from CSV is a requirement. I'll take a look at how I could make this work with the existing json2csv options.

JoaoLucasFurtadoa commented 2 years ago

Tank You guys. Congulations!

whaaaley commented 2 years ago

I just ran into this issue as well. It would be great to have! :D

sofakingworld commented 1 year ago

Same requirement, it would be useful feature to me

mrodrig commented 8 months ago

Thanks to everyone demonstrating support for this use case and issue. I just released version 5.4.0 which updates the deeks and doc-path dependencies to add support for this, while also adding a new arrayIndexesAsKeys option to this package which will allow you to get the desired behavior.

Here's an example:

const { json2csv } = require('json-2-csv');

const data = [
    {
        test: {
            list: [{
                a: 1,
                optionA: 'ac'
            }, {
                a: 2,
                optionB: 'radio'
            }]
        },
    },
    {
        test: {
            list: [{
                a: 3,
                optionA: 'cd'
            }, {
                a: 4,
                optionB: 'heat'
            }]
        }
    }
];
const options = { arrayIndexesAsKeys: true, expandArrayObjects: true };

const csv = json2csv(data, options)
console.log(csv);

which outputs the following CSV:

test.list.0.a,test.list.0.optionA,test.list.1.a,test.list.1.optionB
1,ac,2,radio
3,cd,4,heat
Previesam commented 7 months ago

Hi, Thank you for the great work here @mrodrig. Looking at this I can see some issues which may not have been accounted for.

Is this supported in CLI?

Does it work the other way round when converting csv to json? like a csv with key test.list.0 would it be interpreted as an array as well? This does not seem to be the case on the CLI.

I really need to be able to consistently convert from csv to json and reverse without any issue.

So just like this arrays indexes will be used as keys and in converting csv2json the same will be interpreted back to array.