/go-csv-tag

Read csv file from go using tags

Primary LanguageGoGNU General Public License v3.0GPL-3.0

go-csv-tag

Read csv file from go using tags

godoc for artonge/go-csv-tag

Build Status cover.run go goreportcard for artonge/go-csv-tag

Sourcegraph for artonge/go-csv-tag PRs Welcome

Install

go get github.com/artonge/go-csv-tag

Example

Load

The csv file:

name, ID, number
name1, 1, 1.2
name2, 2, 2.3
name3, 3, 3.4

Your go code:

type Demo struct {                         // A structure with tags
	Name string  `csv:"name"`
	ID   int     `csv:"ID"`
	Num  float64 `csv:"number"`
}

tab := []Demo{}                             // Create the slice where to put the file content
err  := csvtag.Load(csvtag.Config{          // Load your csv with the appropriate configuration
  Path: "file.csv",                         // Path of the csv file
  Dest: &tab,                               // A pointer to the create slice
  Separator: ';',                           // Optional - if your csv use something else than ',' to separate values
  Header: []string{"name", "ID", "number"}, // Optional - if your csv does not contains a header
})

Dump

You go code:

type Demo struct {                         // A structure with tags
	Name string  `csv:"name"`
	ID   int     `csv:"ID"`
	Num  float64 `csv:"number"`
}

tab := []Demo{                             // Create the slice where to put the file content
	Demo{
		Name: "some name",
		ID: 1,
		Num: 42.5,
	},
}

err := csvtag.DumpToFile(tab, "csv_file_name.csv")

You can also dump the data into an io.Writer with

err := csvtag.Dump(tab, yourIOWriter)

The csv file written:

name,ID,number
some name,1,42.5

TODO

  • Update Load to also match csv fields with property name (case sensitive and lowercases)