Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
@jacktuck

This comment has been minimized.

Copy link

commented Apr 30, 2019

Nice

@asnimansari

This comment has been minimized.

Copy link

commented May 13, 2019

In line no 14, i think we should change header == nil to if len(header) == 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.