csvgo

Struct to CSV data as string without creating CSV file


I have a struct which I want to convert into a CSV string. I don't have to write the CSV file. I just need to create the CSV string.

The Go CSV package (https://golang.org/pkg/encoding/csv/) only provides the writing facility.

Here's the struct:

type myData struct {
    A string `json:"a"`
    B string `json:"b"`
    C string `json:"c"`
}

CSV:

1,2,3
4, ,6

I wanted a CSV string so that I can directly upload the string as a file in cloud storage via a serverless environment. So, I want to avoid creating a file in serverless environment.

Is there any package that can help in doing this?


Solution

  • You can use bytes.Buffer to write CSV data and get string using its String() function like this (live):

    package main
    
    import (
        "bytes"
        "encoding/csv"
        "fmt"
        "log"
    )
    
    func main() {
        data := [][]string{
            {"id", "name"},
            {"123", "ABC"},
            {"456", "XYZ"},
        }
    
        b := new(bytes.Buffer)
        w := csv.NewWriter(b)
    
        w.WriteAll(data)
        if err := w.Error(); err != nil {
            log.Fatal(err)
        }
    
        s := b.String()
        fmt.Println(s)
    }
    

    Output:

    id,name
    123,ABC
    456,XYZ