Skip to content

Latest commit

 

History

History
78 lines (53 loc) · 2 KB

README.md

File metadata and controls

78 lines (53 loc) · 2 KB

CSV2Structs

GoDoc Go Report Card

Package csv2structs parses CSV data into a slice of structs.

Example Usage

package main

import (
	"fmt"
	"strings"

	"github.com/digitalocean-labs/csv2structs"
)

func main() {
	csvData := `first_name,age
Alice,30
Bob,25
Charlie,35`

	type Person struct {
		FirstName string
		Age       int
	}

	r := strings.NewReader(csvData)
	people, err := csv2structs.Parse[Person](r)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	for _, p := range people {
		fmt.Printf("%+v\n", p)
	}
}

The above is available as a runnable example.

Headers

All exported fields in the struct passed must match the headers in the CSV data.

By default, the headers in the CSV data are transformed from snake_case to TitleCase.

If you want to disable the header transformation, you can use the WithHeaderType option with the HeaderTypeNone value:

people, err := csv2structs.Parse[Person](r, csv2structs.WithHeaderType(csv2structs.HeaderTypeNone))

If your CSV data has headers in a different format, you can implement your own header transformation function and pass it to the WithHeaderTransform option:

func customHeaderTransform(header string) string {
    // your custom header transformation logic
}

people, err := csv2structs.Parse[Person](r, csv2structs.WithHeaderTransform(customHeaderTransform))

Or, if your CSV data has headers in snake_case format and you want to be explicit, you can use the WithHeaderType option with the HeaderTypeSnake value:

people, err := csv2structs.Parse[Person](r, csv2structs.WithHeaderType(csv2structs.HeaderTypeSnake))

License

This project is licensed under the MIT License - see the LICENSE file for details.