写入 CSV 文件的 JSON 字段包含双引号

发布于 2025-01-14 20:28:48 字数 406 浏览 1 评论 0原文

我正在创建一个 Dictionary,然后通过以下方式将其转换为 JSON:JsonConvert.SerializeObject("dictionary")。 我得到的输出如下图所示:

我想使用 CsvHelper 将其保存到 CSV 文件,但是当我这样做时,它会带来额外的“”,所以在我的对象属性字符串中我得到: "{""连接1"":""00:00:02"",""连接2"":""00:00:02""," 我如何才能将其格式化为与 VisualStudio 中“文本可视化工具”中的文本相同? 我不想要双引号......

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江心雾 2025-01-21 20:28:48

这不是一个实际问题。在 CSV 文件中,包含双引号的字段(如 JSON 字符串)也必须用双引号括起来。 CSV 标准对此进行了解释:

   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"

JSON 字符串包含引号和逗号,所以必须用引号引起来。

您可以告诉 CsvHelper 使用不同的字段分隔符,例如制表符或 | 甚至不同的引号字符。选项卡经常被使用,因为它们很少出现在文本字段中。如果您的 JSON 包含换行符,则必须指定引号字符。

但在这种情况下,您必须使用 CSV 配置所有应用程序才能使用相同的设置。如果文件扩展名是 tsv 而不是 csv,某些程序将检测制表符或使用制表符。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文