adaltas / node-csv-stringify

CSV stringifier implementing the Node.js `stream.Transform` API
https://csv.js.org/stringify/
186 stars 52 forks source link

Object JSON is incorrect #117

Closed random42 closed 4 years ago

random42 commented 4 years ago

I'm using version 5.3.6, but tried also on 5.5.1

When serializing an object the JSON output is incorrect:

const csvStringify = require('csv-stringify');

const data = [
  {
    x: 'asd',
    y: {
      a: 1,
      b: '2'
    },
  }
];

csvStringify(data, {
  cast: {
    //object: JSON.stringify
  }
}, (err, s) => {
  console.log(s);
});

Output:

asd,"{""a"":1,""b"":""2""}"

Even when option quoted is false (by default). Even when passing JSON.stringify as cast.object option, same result.

wdavidw commented 4 years ago

Please provide a complete example on how you are using the library.

wdavidw commented 4 years ago

By the way, this is not JSON, it is just a JS object literal. JSON is a string.

random42 commented 4 years ago

Please provide a complete example on how you are using the library.

I edited the issue so you can try it yourself.

By the way, this is not JSON, it is just a JS object literal. JSON is a string.

What I meant is that when serializing an object column to csv the library converts it into JSON.

wdavidw commented 4 years ago

This library is about generating CSV, which is tabular and not hierarchical. When it encounters an object literal, the default is to serialise to JSON because there is not much else we can do. Of course, this JSON is a field of our final CSV and must be escaped to produce valid CSV. I don't see anything wrong with your code provided above.

random42 commented 4 years ago

My fault, sorry. I thought it was only a matter of escaping the separator character with something like \

I still don't understand how that escaping works but csv parsers get it somehow, so that's enough.