CSV Encoding in Go: Handling Quoted Strings
In Go's encoding/csv package, the handling of quoted strings can sometimes lead to unexpected results. When writing CSV records, it's crucial to understand the standard's requirements for encoding special characters, such as double quotes.
Per the CSV specification, double quote characters within a field must be escaped using a second double quote character. This escape sequence is necessary for parsing reasons.
Example:
<code class="go">import "encoding/csv" record := []string{ "Unquoted string", "Cr@zy text with , and \ and \" etc", } writer := csv.NewWriter(writer) writer.Write(record)</code>
The above code will write a string with double quotes escaped:
<code class="csv">Unquoted string "Cr@zy text with , and \ and \" etc"</code>
Avoiding Extra Quotes:
To avoid the insertion of extra quotes when reading a CSV file, the following steps should be taken:
Code Example:
<code class="go">func writeCSV() { writer := csv.NewWriter(writer) s := "Cr@zy text with , and \ and \" etc" record := []string{ "Unquoted string", "Quoted string", fmt.Sprintf("%q", s), } writer.Write(record) } func readCSV() { reader := csv.NewReader(reader) records, err := reader.ReadAll() for _, record := range records { // Printed records automatically have double quotes unescaped by the CSV reader. fmt.Println(record) } }</code>
Output:
[Unquoted string Cr@zy text with , and \ and " etc] [Quoted string Cr@zy text with , and \ and " etc]
The above is the detailed content of How do you handle quoted strings in CSV encoding with Go\'s `encoding/csv` package?. For more information, please follow other related articles on the PHP Chinese website!