-
-
Save bussiere/bc188cc34eaab203b83d7f3c4622d634 to your computer and use it in GitHub Desktop.
Golang Convert CSV Records to Dictionaries using Header Row as Keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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