go-csv2struct
is a Go package that provides functionality to load CSV data into structs, with support for custom column mapping and data type retrieval.
go get github.com/jimmyclchu/go-csv2struct
Create a CSV file named example.csv with the following content:
name,age,email
John Doe,30,[email protected]
Jane Smith,25,[email protected]
package main
import (
"fmt"
"github.com/username/go-csv2struct"
)
func main() {
csvPath := "./example.csv"
c := csv2struct.NewCSV2Struct()
structSlice, err := c.GenerateStruct(csvPath)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("%+v\n", structSlice)
}
You can set custom column mappings if the CSV headers do not match the struct field tags:
func main() {
csvPath := "./example.csv"
var people []Person
c := csv2struct.NewCSV2Struct()
c.SetCustomMap(map[string]string{"name": "full_name", "age": "years"})
if err := c.LoadCSV(csvPath, &people); err != nil {
fmt.Println("Error:", err)
return
}
for _, person := range people {
fmt.Printf("%+v\n", person)
}
}
If you prefer to define your struct manually, define a struct that matches the CSV columns:
type Person struct {
Name string `csv:"name"`
Age int `csv:"age"`
Email string `csv:"email"`
}
Then load CSV into Struct:
func main() {
csvPath := "./example.csv"
var people []Person
c := csv2struct.NewCSV2Struct()
if err := c.LoadCSV(csvPath, &people); err != nil {
fmt.Println("Error:", err)
return
}
for _, person := range people {
fmt.Printf("%+v\n", person)
}
}
func main() {
var people []Person
c := csv2struct.NewCSV2Struct()
columnTypes := c.GetColumnType(&people)
for col, typ := range columnTypes {
fmt.Printf("Column: %s, Type: %s\n", col, typ)
}
}
go test ./...
This project is licensed under the MIT License - see the ./LICENSE file for details.