Unmarshal CSV record into struct in Go
csv, go, unmarshalling
Solution
There is gocarina/gocsv which handles custom struct in the same way encoding/json does. You can also write custom marshaller and unmarshaller for specific types.
Example:
type Client struct {
Id string `csv:"client_id"` // .csv column headers
Name string `csv:"client_name"`
Age string `csv:"client_age"`
}
func main() {
in, err := os.Open("clients.csv")
if err != nil {
panic(err)
}
defer in.Close()
clients := []*Client{}
if err := gocsv.UnmarshalFile(in, &clients); err != nil {
panic(err)
}
for _, client := range clients {
fmt.Println("Hello, ", client.Name)
}
}
Problem
The problem how to automatically deserialize/unmarshal record from CSV file into Go struct. For example, I have ``` type Test struct { Name string Surname string Age int } ``` And CSV file contains records ``` John;Smith;42 Piter;Abel;50 ``` Is there an easy way to unmarshal those records into struct except by using "encoding/csv" package for reading record and then doing something like ``` record, _ := reader.Read() test := Test{record[0],record[1],atoi(record[2])} ```