go-csv-map: github.com/recursionpharma/go-csv-map Index | Examples | Files

package csvmap

import "github.com/recursionpharma/go-csv-map"

Index

Examples

Package Files

csvmap.go

type Reader Uses

type Reader struct {
    Reader  *csv.Reader
    Columns []string
}

A Reader reads records from a CSV-encoded file.

func NewReader Uses

func NewReader(r io.Reader) *Reader

NewReader returns a new Reader that reads from r.

Code:

reader := NewReader(bytes.NewBuffer(nil))
fmt.Println(string(reader.Reader.Comma))

Output:

,

func (*Reader) Read Uses

func (r *Reader) Read() (record map[string]string, err error)

Read wraps csv.Reader.Read, creating a map of column name to field value. If the line has fewer columns than Reader.Columns, the map will not contain keys for these columns; thus we can distinguish between missing columns and columns with empty values. If the line has more columns than Reader.Columns, Reader.Read() ignores them.

Code:

reader := NewReader(bytes.NewBufferString("first,last\nAlexander,Hamilton"))
var err error
reader.Columns, err = reader.ReadHeader()
if err != nil {
    fmt.Println(err)
    return
}
record, err := reader.Read()
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(record["first"])

Output:

Alexander

func (*Reader) ReadAll Uses

func (r *Reader) ReadAll() (records []map[string]string, err error)

ReadAll reads all the remaining records from r. Each record is a map of column name to field value.

Code:

reader := NewReader(bytes.NewBufferString("first,last\nAlexander,Hamilton\nAaron,Burr"))
var err error
reader.Columns, err = reader.ReadHeader()
if err != nil {
    fmt.Println(err)
    return
}
records, err := reader.ReadAll()
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(records[1]["last"])

Output:

Burr

func (*Reader) ReadHeader Uses

func (r *Reader) ReadHeader() (columns []string, err error)

ReadHeader simply wraps csv.Reader.Read().

Code:

reader := NewReader(bytes.NewBufferString("first,last\nAlexander,Hamilton"))
var err error
reader.Columns, err = reader.ReadHeader()
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(reader.Columns[1])

Output:

last

Package csvmap imports 3 packages (graph) and is imported by 3 packages. Updated 2020-01-06. Refresh now. Tools for package owners.