csvdict

package module
v0.0.0-...-474b529 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2021 License: GPL-3.0 Imports: 4 Imported by: 0

README

csvdict

Golang short library that extends encoding/csv to handle importing CSV content with headers as a dictionary (map)

Usage

NewDictReader takes an argument of an io.Reader object and returns a pointer to a DictReader object that contains both a CSV Reader and a separate slice with the first line of the CSV file, assumed to be the header row.

Similarly, NewDictWriter takes two arguments, an io.Writer and a slice of headers, returning a pointer to a DictWriter object (and an error value, hopefully nil), a CSV Writer that will write the value corresponding to each header in the slice to file, in order:

dictReader, err := csvdict.NewDictReader(ioReader) dictWriter := csvdict.NewDictWriter(ioWriter, headerSlice)

To read a line, use Read(), which returns a map with the header row contents as the indices and the contents of the row being read as the value. For example:

rowMap, err := dictReader.Read()

Optionally, to read all the contents, you can use ReadAll():

records, err := r.ReadAll()

To write to file, first write the header row line to file:

dictWriter.WriteHeaders()

Then to write records one line at a time, use Write(csvMap), which takes as an argument a map with indices matching the headers of the CSV file to be written:

err = dictWriter.Write(csvMap)

f writing line by line, to ensure that everything has been written to file before the end of execution, call Flush():

dictWriter.Flush()

Optionally, you can use WriteAll(csvMapSlice), which takes a slice of CSV maps, and calls Flush() automatically:

dictWriter.Writeall(csvMapSlice)

Documentation

Overview

Package csvdict is a Short Go library that extends encoding/csv to handle importing CSV content with headers as a map (dictionary)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DictReader

type DictReader struct {
	// contains filtered or unexported fields
}

DictReader contains a reference to a CSV reader and a header row slice, used to map each CSV row to its headers

Example
package main

import (
	"fmt"
	"io"
	"log"
	"strings"

	"github.com/kurankat/csvdict"
)

func main() {
	in := `name, age, occupation
"Mark Smith",33,"Jack of all trades"
"Douglas Adams",42,Writer
Methuselah,969,Patriarch
`

	r, err := csvdict.NewDictReader(strings.NewReader(in))
	if err != nil {
		panic(err)
	}

	headers := r.GetHeaderRow()

	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}

		fmt.Printf("%v:%v %v:%v %v:%v\n", headers[0], record[headers[0]],
			headers[1], record[headers[1]],
			headers[2], record[headers[2]])
	}
}
Output:

name:Mark Smith  age:33  occupation:Jack of all trades
name:Douglas Adams  age:42  occupation:Writer
name:Methuselah  age:969  occupation:Patriarch

func NewDictReader

func NewDictReader(r io.Reader) (dr *DictReader, err error)

NewDictReader takes an io.Reader as an argument and returns a reference to a DictReader

func (*DictReader) GetHeaderRow

func (d *DictReader) GetHeaderRow() (header []string)

GetHeaderRow returns the header row of the DictReader object

func (*DictReader) Read

func (d *DictReader) Read() (csvMap map[string]string, err error)

Read reads a single line of a CSV file and returns a map where each field is mapped to its header

func (*DictReader) ReadAll

func (d *DictReader) ReadAll() (records []map[string]string, err error)

ReadAll reads all the remaining records from r. Each record is a map of fields. A successful call returns err == nil, not err == io.EOF. Because ReadAll is defined to read until EOF, it does not treat end of file as an error to be reported.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/kurankat/csvdict"
)

func main() {
	in := `name, age, occupation
"Mark Smith",33,"Jack of all trades"
"Douglas Adams",42,Writer
Methuselah,969,Patriarch
`

	r, err := csvdict.NewDictReader(strings.NewReader(in))
	if err != nil {
		panic(err)
	}

	records, err := r.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	headers := r.GetHeaderRow()

	for _, record := range records {
		fmt.Printf("%v:%v %v:%v %v:%v\n", headers[0], record[headers[0]],
			headers[1], record[headers[1]],
			headers[2], record[headers[2]])
	}

}
Output:

name:Mark Smith  age:33  occupation:Jack of all trades
name:Douglas Adams  age:42  occupation:Writer
name:Methuselah  age:969  occupation:Patriarch

type DictWriter

type DictWriter struct {
	// contains filtered or unexported fields
}

DictWriter contains a reference to a CSV Writer object and a header row slice

Example
package main

import (
	"os"

	"github.com/kurankat/csvdict"
)

func main() {
	headers := []string{"name", "age", "occupation"}
	records := []map[string]string{
		{"name": "Mark Smith", "age": "33", "occupation": "Jack of all trades"},
		{"name": "Douglas Adams", "age": "42", "occupation": "Writer"},
		{"name": "Methuselah", "age": "969", "occupation": "Patriarch"},
	}

	w := csvdict.NewDictWriter(os.Stdout, headers)

	w.WriteHeaders()

	for _, record := range records {
		err := w.Write(record)
		if err != nil {
			panic(err)
		}
	}

	w.Flush()
}
Output:

name,age,occupation
Mark Smith,33,Jack of all trades
Douglas Adams,42,Writer
Methuselah,969,Patriarch

func NewDictWriter

func NewDictWriter(w io.Writer, h []string) *DictWriter

NewDictWriter takes an io.Writer and a slice containing the header row as arguments and returns a reference to a DictWriter

func (*DictWriter) Flush

func (w *DictWriter) Flush()

Flush ensures that the writer is flushed to file

func (*DictWriter) Write

func (w *DictWriter) Write(csvMap map[string]string) error

Write takes a map with headers as indices and field contents as values, and writes it to file as CSV

func (*DictWriter) WriteAll

func (w *DictWriter) WriteAll(records []map[string]string) error

WriteAll writes multiple CSV records to w using Write and then calls Flush.

Example
package main

import (
	"os"

	"github.com/kurankat/csvdict"
)

func main() {
	headers := []string{"name", "age", "occupation"}
	records := []map[string]string{
		{"name": "Mark Smith", "age": "33", "occupation": "Jack of all trades"},
		{"name": "Douglas Adams", "age": "42", "occupation": "Writer"},
		{"name": "Methuselah", "age": "969", "occupation": "Patriarch"},
	}

	w := csvdict.NewDictWriter(os.Stdout, headers)

	err := w.WriteAll(records)
	if err != nil {
		panic(err)
	}
}
Output:

name,age,occupation
Mark Smith,33,Jack of all trades
Douglas Adams,42,Writer
Methuselah,969,Patriarch

func (*DictWriter) WriteHeaders

func (w *DictWriter) WriteHeaders()

WriteHeaders writes the header row to file

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL