Home >Backend Development >Golang >How to Efficiently Deserialize CSV Data into Go Structures?
Question:
How can I efficiently deserialize CSV records into Go structures?
Problem Statement:
Suppose you have a custom Go structure Test, with fields Name, Surname, and Age. You have a CSV file containing records in the format:
John;Smith;42 Piter;Abel;50
How can you automatically unmarshal these records into instances of the Test structure, without relying on manual deserialization operations?
Answer:
To simplify the deserialization process, consider using the gocarina/gocsv library. gocsv offers similar functionality to the encoding/json package but specifically caters to CSV data.
Here's an example using gocsv:
package main import ( "fmt" "log" "os" "github.com/gocarina/gocsv" ) type Test struct { Name string `csv:"Name"` Surname string `csv:"Surname"` Age int `csv:"Age"` } func main() { // Open CSV file for reading in, err := os.Open("test.csv") if err != nil { log.Fatal(err) } defer in.Close() // Declare a slice to hold the Test structures var tests []Test // Unmarshal the CSV records into the Test structures if err := gocsv.UnmarshalFile(in, &tests); err != nil { log.Fatal(err) } // Print the unmarshaled data for _, test := range tests { fmt.Printf("Name: %s, Surname: %s, Age: %d\n", test.Name, test.Surname, test.Age) } }
In this example, gocsv handles the deserialization process for you, simplifying the conversion of CSV records into Go structures. You can use custom field tags in the Test struct to specify the CSV column headers for each field, ensuring accurate mapping.
The above is the detailed content of How to Efficiently Deserialize CSV Data into Go Structures?. For more information, please follow other related articles on the PHP Chinese website!