juanjoDiaz / json2csv

Flexible conversion between JSON and CSV
https://juanjodiaz.github.io/json2csv/
MIT License
296 stars 32 forks source link

ignore or exclude a key from adding in parsed data #11

Closed abhimanu-sharma closed 1 year ago

abhimanu-sharma commented 1 year ago
const data = {
'key1': ['data1', 'data2'],
'key2': {
             'subkey1': 'subdata1',
             'subkey2': 'subdata2'
      },
'key3': "data3"
}

I want 3 json 1st should not include data from steam data with key2 and key3, second csv should have data on only key2 and so on.

I tried to send data like parser.parse(data["key1"]) but getting error

"Data should not be empty or the \"fields\" option should be included","name":"Error","stack":"Error: Data should not be empty or the \"fields\" option should be included\n    at JSON2CSVNodeTransform.pushHeaderIfNotWritten (/opt/wi-api/node_modules/@json2csv/plainjs/dist/cjs/StreamParser.js:124:9)\n    at Object.end (/opt/wi-api/node_modules/@json2csv/plainjs/dist/cjs/StreamParser.js:55:14)\n    at JSON2CSVNodeTransform.end [as endUnderlayingParser] (/opt/wi-api/node_modules/@json2csv/plainjs/dist/cjs/StreamParser.js:117:22)\n    at JSON2CSVNodeTransform._final (/opt/wi-api/node_modules/@json2csv/node/dist/cjs/Transform.js:75:12)\n    at callFinal (_stream_writable.js:609:10)\n    at processTicksAndRejections (internal/process/task_queues.js:84:21)"},"msg":"Data should not be empty or the \"fields\" option should be included"
juanjoDiaz commented 1 year ago

Hi @abhimanu-sharma ,

That is because you are trying to parse an array of string (['data1', 'data2']) and json2csv expects an array of object. An object like { a: 1, b: 2 } would yield:

a,b
1,2

However, what would you expect 'data1' to yield?

In any case, I will look into improving the error message since I think that it's not 100% clear.

abhimanu-sharma commented 1 year ago

Hi @juanjoDiaz ,

Suppose there is my main json data ['data1', 'data2']

const opts = {
            transforms: [
                unwind({ paths: ['data1', 'data2'], blankOut: true }),
                flatten({ object: false, array: true, separator: '_'}),
            ]
        }

Now, structure of data1 is like,

{
key1: 'foo',
key2: 'bar',
key3: 'password'
}

I want to remove key3 to be included in the csv.

juanjoDiaz commented 1 year ago

Hi @abhimanu-sharma ,

You need to be more clear if you want help 🙂 I need a full json input and the output that you would expect.

I don't really understand what your actual input data looks like or what you are trying to get since your latest issue doesn't seem related to the first one.