Skip to content

Instantly share code, notes, and snippets.

@DeadNumbers
Forked from drernie/csvtomap.go
Created April 17, 2019 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeadNumbers/214989f7601a3b146928b1a69f7383bb to your computer and use it in GitHub Desktop.
Save DeadNumbers/214989f7601a3b146928b1a69f7383bb to your computer and use it in GitHub Desktop.
Golang Convert CSV Records to Dictionaries using Header Row as Keys
// CSVToMap takes a reader and returns an array of dictionaries, using the header row as the keys
func CSVToMap(reader io.Reader) []map[string]string {
r := csv.NewReader(reader)
rows := []map[string]string{}
var header []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if header == nil {
header = record
} else {
dict := map[string]string{}
for i := range header {
dict[header[i]] = record[i]
}
rows = append(rows, dict)
}
}
return rows
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment