ホームページ  >  記事  >  バックエンド開発  >  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 エンコーディング

このコード スニペットは、2 つのレコード (1 つは引用符で囲まれていない文字列、もう 1 つは引用符で囲まれた文字列) を含む 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"

Example

これは、不要なエスケープを削除したコードの改良版です:

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()
}

Output

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。