Skip to content

Instantly share code, notes, and snippets.

@drernie
Created March 10, 2017 22:48
Show Gist options
  • Save drernie/5684f9def5bee832ebc50cabb46c377a to your computer and use it in GitHub Desktop.
Save drernie/5684f9def5bee832ebc50cabb46c377a 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
}
@jacktuck
Copy link

Nice

@asnimansari
Copy link

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

@vengateshm
Copy link

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

The we should declare it as a slice i guess
header := make([]string,0)

@folite
Copy link

folite commented May 3, 2024

This method is really awesome!

@muhammedkucukaslan
Copy link

Nice work! I was working with 2 colums csv and found here. I used same made a function for one map[type]type
It is here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment