3

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?

2
  • 2
    encoding/csv does what you need. Your assumption that encoding/csv allways creates files is plain wrong. Commented Apr 6, 2020 at 6:59
  • 1
    Btw: Asking for third party libraries is OT on SO. Commented Apr 6, 2020 at 7:27

2 Answers 2

12

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
Sign up to request clarification or add additional context in comments.

Comments

6

Use bytes.Buffer to write data without creating file. With bytes.Buffer we can write bytes into a single buffer, and then convert to a string when we are done by invoke the String() func.

var csvData = [][]string{
      {"SuperHero Name", "Power", "Weakness"},
      {"Batman", "Wealth", "Human"},
      {"Superman", "Strength", "Kryptonite"},
   }
buf := new(bytes.Buffer)
wr := csv.NewWriter(buf)
w.WriteAll(csvData)
csvString := buf.String()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.