How to Work with CSV Strings in Go

Parse CSV strings in Go by wrapping the string in strings.NewReader and using the encoding/csv package to read records.

Use the encoding/csv package to parse CSV strings by wrapping them in strings.NewReader and calling Read() on the reader.

package main

import (
	"encoding/csv"
	"fmt"
	"strings"
)

func main() {
	csvData := "name,age\nAlice,30\nBob,25"
	reader := csv.NewReader(strings.NewReader(csvData))
	records, err := reader.ReadAll()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(records)
}