Home > front end >  Golang, importing csv and converting it to map
Golang, importing csv and converting it to map

Time:10-16

I have been trying to import a csv file in go and convert it into map function but having a lot of difficulties in doing that. The problems that I have been facing with this code is that
a) The file not seeking to the beginning even when i have added file.Seek(0,0) so that i could read it from the beginning.
b) It is not giving me the output in desired format. I want the output to be in the as

Output

map[key1:{abc 123} key2:{bcd 543} key3:{def 735}]

My csv file is as: (Input)

col1   |  col2  |  col3   
key1   |   abc  |  123
key2   |   bcd  |  543
key3   |   def  |  735

As I have just switched to go and is a beginner, It would be very kind of you if you solve my issue.

package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strings"
)

func main() {
    m := CSVFileToMap()
    fmt.Println(m)
}

func CSVFileToMap() (returnMap []map[string]string) {

    filePath := "export.csv"
    // read csv file
    csvfile, err := os.Open(filePath)
    if err != nil {
        return nil
    }

    defer csvfile.Close()
    csvfile.Seek(0, 0)
    reader := csv.NewReader(csvfile)

    rawCSVdata, err := reader.ReadAll()
    if err != nil {
        return nil
    }

    header := []string{} // holds first row (header)
    for lineNum, record := range rawCSVdata {

        // for first row, build the header slice
        if lineNum == 0 {
            for i := 0; i < len(record); i   {
                header = append(header, strings.TrimSpace(record[i]))
            }
        } else {
            // for each cell, map[string]string k=header v=value
            line := map[string]string{}
            for i := 0; i < len(record); i   {
                line[header[i]] = record[i]
            }
            returnMap = append(returnMap, line)
        }
    }
    return returnMap
}

CodePudding user response:

By default field delimiter is , you need to specify your intent to use |

reader := csv.NewReader(csvfile)
reader.Comma = '|'

Output

[map[col1:key1    col2:   abc   col3:  123] map[col1:key2    col2:   bcd   col3:  543] map[col1:key3    col2:   def   col3:  735]]
  • Related