Skip to content

Instantly share code, notes, and snippets.

@asnimansari
Last active May 13, 2019 07:33
Show Gist options
  • Select an option

  • Save asnimansari/d9c8bdf69a3e6988c4990fa159b51bd6 to your computer and use it in GitHub Desktop.

Select an option

Save asnimansari/d9c8bdf69a3e6988c4990fa159b51bd6 to your computer and use it in GitHub Desktop.
This is a golang function which can convert a reader to an array of dicts with headers and values
// 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 len(header) == 0 {
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