Home > database >  JSON fields written to a CSV file contain doubled quotes
JSON fields written to a CSV file contain doubled quotes

Time:03-17

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

CodePudding user response:

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. Tabs are often used because they rarely appear in text fields. If your JSON contains newlines though, you'll have to specify a quote character.

In this case though, you'd have to configure any applications using your CSV to use the same settings. Some programs will detect tabs or use a tab if the file extension is tsv instead of csv.

  • Related