首頁  >  文章  >  後端開發  >  為什麼 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