beatrichartz/csv

Unable to properly enclose cells with double quotes

amilkr opened this issue · 2 comments

Hi, I'm trying to generate a csv file where some cell values must be enclosed by double quotes. Something like:

field_1, field_2
"first value", second value

But I don't find the way to achieve this.

CSV.Encode.encode/1 is duplicating the double quotes, also it's adding a double quote at the beginning and at the end:

> CSV.Encode.encode("\"myvalue\"")
"\"\"\"myvalue\"\"\""

So, when I try something like this

file = File.open!("test.csv", [:write, :utf8])

 [%{"field_1" => "\"first value\"", "field_2" => "second value"}]
|> CSV.encode(headers: ["field_1", "field_2"])
|> Enum.each(&IO.write(file, &1)) 

I end up with this content in my file:

field_1,field_2
"""first value""",second value

Is this the expected behaviour?
Is there any way to generate the file in the format I need (i.e. enforcing the double-quote enclosing for some cell values )?

Thanks

Hi @amilkr this is expected behaviour. RFC 4180 stipulates that:

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"

So any RFC compliant CSV reading mechanism should be able to deal with it accordingly. Are you experiencing problems loading the generated CSV somewhere?

@beatrichartz , thanks for your quick answer. I understood the rule about double-quotes, thanks.
Now, I have to talk to the people that wrote the requirements :)

Thank you, again.