Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct to CSV data as string without creating CSV file

Tags:

csv

go

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?

like image 497
max Avatar asked Feb 25 '26 21:02

max


1 Answers

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
like image 58
Azeem Avatar answered Feb 27 '26 21:02

Azeem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!