Categorygithub.com/prongbang/csvx
repositorypackage
1.1.3
Repository: https://github.com/prongbang/csvx.git
Documentation: pkg.go.dev

# README

CSVX

Go Coverage Go Report Card

Convert array struct to csv format and Parse csv format to array struct with Golang

"Buy Me A Coffee"

Install

go get github.com/prongbang/csvx

Define struct for Convert

Add header for mapping in csv header and no start with 1 for sort header

type MyStruct struct {
    Name  string `json:"name" header:"Name Space" no:"2"`
    ID    int    `json:"id" header:"ID" no:"1"`
    Other string
}

Support type

  • int, int8, int16, int32, int64
  • string
  • float64

Using for Convert

m := []MyStruct{
    {ID: 1, Name: "N1"}, 
    {ID: 2, Name: "N2"}
}
csv := csvx.Convert[MyStruct](m)

Result

"ID","Name Space"
"1","N1"
"2","N2"

Define struct for Parse

Add header for mapping in csv header

type Struct struct {
	ID   string `header:"ID"`
	Name string `header:"Name Space"`
}

Using for Parse

rows := [][]string{
    {"ID", "Name Space"},
    {"1", "Name1"},
    {"2", "Name2"},
    {"3", "Name3"},
    {"4", "Name4"},
}
s := csvx.Parser[Struct](rows)

Result

[
  {"ID":"1","Name":"Name1"},
  {"ID":"2","Name":"Name2"},
  {"ID":"3","Name":"Name3"},
  {"ID":"4","Name":"Name4"}
]

Benchmark

goos: darwin
goarch: arm64
pkg: github.com/prongbang/csvx
cpu: Apple M1 Pro
BenchmarkConvert-10          	  430015	      5751 ns/op
BenchmarkManualConvert
BenchmarkManualConvert-10    	 2002738	       614.8 ns/op
BenchmarkTryConvert
BenchmarkTryConvert-10    	      760494	      1573 ns/op