首页  >  文章  >  后端开发  >  为什么 Go 的 CSV 编写器会为包含特殊字符的引用字符串添加额外的引号?

为什么 Go 的 CSV 编写器会为包含特殊字符的引用字符串添加额外的引号?

Susan Sarandon
Susan Sarandon原创
2024-10-25 09:30:02186浏览

Why does Go's CSV writer add extra quotes to quoted strings containing special characters?

Go 中带引号的字符串的奇怪 CSV 编码

此代码片段尝试创建一个包含两条记录的 CSV 文件,一条记录包含未加引号的字符串,另一条记录包含带引号的字符串包含特殊字符的字符串:

<code class="go">package main

import (
    "encoding/csv"
    "fmt"
    "log"
    "os"
)

func main() {
    f, err := os.Create("./test.csv")
    if err != nil {
        log.Fatal("Error: %s", err)
    }
    defer f.Close()

    w := csv.NewWriter(f)
    var record []string
    record = append(record, "Unquoted string")
    s := "Cr@zy text with , and \ and \" etc"
    record = append(record, s)
    fmt.Println(record)
    w.Write(record)

    record = make([]string, 0)
    record = append(record, "Quoted string")
    s = fmt.Sprintf("%q", s)
    record = append(record, s)
    fmt.Println(record)
    w.Write(record)

    w.Flush()
}</code>

但是,输出包含带引号的字符串周围的额外引号:

Unquoted string,"Cr@zy text with , and \ and "" etc"
Quoted string,"""Cr@zy text with , and \ and \"" etc"""

说明

此行为是 CSV 的结果标准。根据规范,字段内的双引号必须用双引号转义。因此,CSV 写入器会自动对带引号的字符串中的双引号进行转义。

解决方案

CSV 读取器会在解析过程中自动对双引号进行转义,因此无需担心多余的引号。带引号的字符串将被正确解释为:

"Cr@zy text with , and \ and \" etc"

示例

这是代码的改进版本,删除了不必要的转义:

package main

import (
    "encoding/csv"
    "fmt"
    "os"
)
func checkError(e error){
    if e != nil {
        panic(e)
    }
}
func writeCSV(){
    fmt.Println("Writing csv")
    f, err := os.Create("./test.csv")
    checkError(err)
    defer f.Close()

    w := csv.NewWriter(f)
    s := &quot;Cr@zy text with , and \ and \&quot; etc&quot;
    record := []string{ 
      "Unquoted string",
      s,
    }
    fmt.Println(record)
    w.Write(record)

    record = []string{ 
      "Quoted string",
      s,
    }
    fmt.Println(record)
    w.Write(record)
    w.Flush()
}
func readCSV(){
    fmt.Println("Reading csv")
    file, err := os.Open("./test.csv")
    defer file.Close();
    cr := csv.NewReader(file)
    records, err := cr.ReadAll()
    checkError(err)
    for _, record := range records {
        fmt.Println(record)
    }
}
func main() {
   writeCSV()
   readCSV()
}

输出

Writing csv
[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string Cr@zy text with , and \ and " etc]
Reading csv
[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string Cr@zy text with , and \ and " etc]

以上是为什么 Go 的 CSV 编写器会为包含特殊字符的引用字符串添加额外的引号?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn