Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a map to a csv

Tags:

csv

go

I've been attempting to figure out how to properly write a map to a csv file with no luck.

I essentially have a program that queries an sql database, I store one of the return values as the key to the map, and then a slice of string for the data related to it that's returned, as an example the map would be:

var m = make(map[string][]string)

m['test1'] = [5, 4, 3]

so writing it to a csv would be

test1, 5, 4, 3

Its printed to the csv just like a list/slice would be, I'm storing it in a map to make it easier to construct dynamic queries elsewhere.

I've attempted using a for loop such that:

for key, value := range m{
    writer.Write(key)
    writer.Write(value)
}

but I'm getting the following error:

cannot use key (type string) as type []string in argument to writer.Write

I've done a lot of googling and searching here and can't seem to find a way to do this properly.

like image 313
Dangle Avatar asked Nov 27 '17 18:11

Dangle


1 Answers

Package csv

func (*Writer) Write

func (w *Writer) Write(record []string) error

Writer writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field.


error: cannot use key (type string) as type []string in argument to writer.Write


"I've done a lot of googling and searching here."

To solve this problem, read the documentation of Write and follow the instructions in the error message, You have type string, Write wants type []string. For example,

for key, value := range m {
    r := make([]string, 0, 1+len(value))
    r = append(r, key)
    r = append(r, value...)
    err := writer.Write(r)
    if err != nil {
        // handle error
    }
}
writer.Flush()
like image 136
peterSO Avatar answered Sep 23 '22 00:09

peterSO