Ad

JSON Fields Written To A CSV File Contain Doubled Quotes

- 1 answer

i'm creating a Dictionary<string, TimeSpan>, and then converting this to JSON by: JsonConvert.SerializeObject("dictionary"). and i get the output as follows in the picture: enter image description here

Now i want to save this to a CSV file using CsvHelper, but when i do that it brings along additional ""'s, so in my object-property-string i get: "{""Connection1"":""00:00:02"",""Connection2"":""00:00:02""," How do can i format this equal to the text in the "Text Visualizer" in VisualStudio? I dont want the double quotes....

Ad

Answer

This isn't an actual problem. In a CSV file, fields that contain double quotes (like a JSON string) have to be enclosed in double quotes too. That's explained in the CSV standard:

   6.  Fields containing line breaks (CRLF), double quotes, and commas
       should be enclosed in double-quotes.  For example:

       "aaa","b CRLF
       bb","ccc" CRLF
       zzz,yyy,xxx

   7.  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"

A JSON string contains both quotes and commas, so it has to be quoted.

You can tell CsvHelper to use a different field separator, eg a tab or | and even a different quote character. In this case though, you'd have to configure any applications using your CSV to use the same settings.

Ad
source: stackoverflow.com
Ad