Convert CSV to structure in GO
https://www.socketloop.com/tutorials/how-to-unmarshal-or-load-csv-record-into-struct-go
https://www.socketloop.com/tutorials/read-csv-file-go
package main
import (
"encoding/csv"
"fmt"
"os"
)
type TestRecord struct {
Email string
Date string
}
func main() {
csvfile, err := os.Open("somecsvfile.csv")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer csvfile.Close()
reader := csv.NewReader(csvfile)
reader.FieldsPerRecord = -1
rawCSVdata, err := reader.ReadAll()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// sanity check, display to standard output
for _, each := range rawCSVdata {
fmt.Printf("email : %s and timestamp : %s\n", each[0], each[1])
}
// now, safe to move raw CSV data to struct
var oneRecord TestRecord
var allRecords []TestRecord
for _, each := range rawCSVdata {
oneRecord.Email = each[0]
oneRecord.Date = each[1]
allRecords = append(allRecords, oneRecord)
}
// second sanity check, dump out allRecords and see if
// individual record can be accessible
fmt.Println(allRecords)
fmt.Println(allRecords[2].Email)
fmt.Println(allRecords[2].Date)
}
The CSV file contains the following data
more somecsvfile.csv
"jenniferlcl@*****.com","2012-07-03 18:38:06"
"norazlinjumali@*****.com","2010-06-26 19:46:08"
"wilfred5571@*****.com","2010-07-02 21:49:55"
"nas_kas81@*****.com","2010-07-06 12:49:31"
"tammyu3622@*****.com","2010-07-06 13:55:21"
"wakrie@*****.com","2012-03-02 11:00:59"
"yst.shirin@*****.com","2010-07-07 10:19:11"
"annl_107@*****.com","2010-07-07 20:55:59"
"jen_5831@*****.com","2010-07-07 21:12:27"
"hsheyli@*****.com","2011-09-07 00:39:11"
Csv file
and executing go run csv2struct.go will produce the following output :
email : jenniferlcl@*****.com and timestamp : 2012-07-03 18:38:06
email : norazlinjumali@*****.com and timestamp : 2010-06-26 19:46:08
email : wilfred5571@*****.com and timestamp : 2010-07-02 21:49:55
email : nas_kas81@*****.com and timestamp : 2010-07-06 12:49:31
email : tammyu3622@*****.com and timestamp : 2010-07-06 13:55:21
email : wakrie@*****.com and timestamp : 2012-03-02 11:00:59
email : yst.shirin@*****.com and timestamp : 2010-07-07 10:19:11
email : annl_107@*****.com and timestamp : 2010-07-07 20:55:59
email : jen_5831@*****.com and timestamp : 2010-07-07 21:12:27
email : hsheyli@*****.com and timestamp : 2011-09-07 00:39:11
Output:
[{jenniferlcl@*****.com 2012-07-03 18:38:06} {norazlinjumali@*****.com 2010-06-26 19:46:08} {wilfred5571@*****.com 2010-07-02 21:49:55} {naskas81@*****.com 2010-07-06 12:49:31} {tammyu3622@*****.com 2010-07-06 13:55:21} {wakrie@*****.com 2012-03-02 11:00:59} {yst.shirin@*****.com 2010-07-07 10:19:11} {annl107@*****.com 2010-07-07 20:55:59} {jen_5831@*****.com 2010-07-07 21:12:27} {hsheyli@*****.com 2011-09-07 00:39:11}]
wilfred5571@*****.com
2010-07-02 21:49:55