Skip to content

jamesrr39/csvx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

csvx

PkgGoDev

csvx is a package with a CSV string-fields-to-struct encoder and decoder for Go. It makes converting raw strings from CSV files into objects (and vice-versa) much easier.

It is licensed under the permissive Apache 2 license.

Usage

Use with the stdlib csv reader. Use this library to quickly turn []string into an object, or an object into []string.

type targetType struct {
    Name        string `csv:"name"`
    Age         *int   `csv:"age"`
    NonCSVField string // field will be ignored by struct scanner, since it is missing the "csv" tag
}

// decoding

fields := []string{"name", "age"}
decoder := NewDecoder(fields)

target := new(targetType)
err := decoder.Decode([]string{"John Smith","40"}, target)
if err != nil {
    panic(err)
}

fmt.Printf("result: %#v\n", target)

// encoding
encoder := NewEncoder(fields)
records, err := encoder.Encode(target)
if err != nil {
    panic(err)
}

fmt.Printf("records: %#v\n", records)

See also the example on pkg.go.dev and the tests in this package for more examples.

Implemented Types

  • string
  • int
  • int64
  • int32
  • int16
  • int8
  • uint
  • uint64
  • uint32
  • uint16
  • uint8
  • float64
  • float32
  • bool (true, yes, 1, 1.0 = true, false, no, 0, 0.0 = false, other values result in an error, customisable in the Encoder and Decoder fields)
  • struct with encoding.TextUnmarshaler and encoding.TextMarshaler implemented on them
  • Pointer types to above underlying types, e.g. *string (empty string and null result in nil being set on the Go struct)
  • Custom non-struct types, e.g. type Name string, so long as the underlying type is in the list above.

Performance

The struct scanner uses reflect quite heavily, so this library will not be as fast as writing a specific parser for the struct. However, for the vast majority of cases, the performance hit will be acceptable and the development speed increase and simple client code will be worth it!

Auditability/readability

This aims to be a simple, easy-to-audit library with stdlib-only dependencies (github.com/stretchr/testify is also used, but only for test files).

About

Convienience tools for CSV in Go

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages