Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/prongbang/csvx
Convert array struct to csv format with Golang
https://github.com/prongbang/csvx
convert csv go golang parse parser
Last synced: about 2 months ago
JSON representation
Convert array struct to csv format with Golang
- Host: GitHub
- URL: https://github.com/prongbang/csvx
- Owner: prongbang
- License: mit
- Created: 2023-02-25T16:47:49.000Z (almost 2 years ago)
- Default Branch: master
- Last Pushed: 2024-09-04T13:54:53.000Z (5 months ago)
- Last Synced: 2024-10-26T09:53:04.252Z (3 months ago)
- Topics: convert, csv, go, golang, parse, parser
- Language: Go
- Homepage:
- Size: 38.1 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# CSVX
[![Go Coverage](https://github.com/prongbang/csvx/wiki/coverage.svg)](https://raw.githack.com/wiki/prongbang/csvx/coverage.html)
[![Go Report Card](https://goreportcard.com/badge/github.com/prongbang/csvx)](https://goreportcard.com/report/github.com/prongbang/csvx)Convert array struct to csv format and Parse csv format to array struct with Golang
[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/prongbang)
## Install
```shell
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
```go
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
```go
m := []MyStruct{
{ID: 1, Name: "N1"},
{ID: 2, Name: "N2"}
}
csv := csvx.Convert[MyStruct](m)
```## Result
```csv
"ID","Name Space"
"1","N1"
"2","N2"
```## Define struct for Parse
Add `header` for mapping in csv header
```go
type Struct struct {
ID string `header:"ID"`
Name string `header:"Name Space"`
}
```## Using for Parse
```go
rows := [][]string{
{"ID", "Name Space"},
{"1", "Name1"},
{"2", "Name2"},
{"3", "Name3"},
{"4", "Name4"},
}
s := csvx.Parser[Struct](rows)
```## Result
```json
[
{"ID":"1","Name":"Name1"},
{"ID":"2","Name":"Name2"},
{"ID":"3","Name":"Name3"},
{"ID":"4","Name":"Name4"}
]
```## Benchmark
```shell
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
```