csv-writer icon indicating copy to clipboard operation
csv-writer copied to clipboard

Stringified Objects are double quoted and non Stringified objects are output as [object Object]

Open nrodriguez opened this issue 5 years ago • 3 comments

If I want my csv to simply output a column with a stringified object, it will end up with double quotes

Desired {"can_debit_product_attributes":{"experience_type":"ecommerce","is_comp":false}}

Actual output

“{”“can_debit_product_attributes”“:{“”experience_type”“:”“ecommerce”“,”“is_comp”“:false}}”

If I don't stringify my objects then it's output as

[object Object]

Anyway around this?

I did see we check if it has a quote already and then replace it with a double quote here: https://github.com/ryu1kn/csv-writer/blob/master/src/lib/field-stringifier.ts#L27

nrodriguez avatar Dec 03 '20 22:12 nrodriguez

Hi @nrodriguez , thanks for the PR. It works like that as RFC 4180 says this:

  1. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote. For example:

    "aaa","b""bb","ccc

https://tools.ietf.org/html/rfc4180#section-2

If you open "{""can_debit_...}" in excel or something you should see what you expect (i.e. {"can_debit_...})

ryu1kn avatar Dec 04 '20 08:12 ryu1kn

Thanks for the response @ryu1kn!

I was intending to use the exported csv in a script which was generating some sql so obviously it would then try to put it into the database with the double set of quotes. Would it be worth adding some kind of switch that allows us to export the csv with what we give it assuming we might not be opening it in excel or something?

nrodriguez avatar Dec 04 '20 15:12 nrodriguez

@nrodriguez passing through as some googling brought me here for my own problem with csv-writer. However, I think @ryu1kn is correct that this is appropriate behavior per the RFC 4180 spec. But more importantly, I had a similar use case scenario as you and found it working. I wanted to dump my csv's into some sql (mariadb) and come back to the information later and JSON.parse the field. I am able to do just that without issue.

What tripped me up is I was looking at the output of the csv directly and trying to cut and paste that field into node didn't work for JSON.parse. But assuming you import SQL with fields delimited by the proper field delimiter it will only treat the outside set the surrounding pair of quotes as the delimiter and the other questions as quotes and any field delimiters inside the quotes will be ignored.

Note: I am using maria as an upstream source to SOLR. Both return the field in a way that JSON.parse works without issue.

mgr34 avatar Jan 06 '21 15:01 mgr34