A Go library for converting CSV data to maps and vice versa. This library provides a simple and flexible way to work with CSV data in Go applications.
- CSV to Map conversion: Parse CSV data into a slice of maps where each map represents a row
- Map to CSV conversion: Convert a slice of maps back to CSV format
- Flexible configuration: Support for custom delimiters, comments, and empty line handling
- Multiple input sources: Support for
io.Reader
, strings, and files - Type safety: Uses
interface{}
for flexible data types - Error handling: Comprehensive error handling with descriptive messages
- Performance: Optimized for both memory usage and speed
go get your-module/csvmap
package main
import (
"fmt"
"log"
"your-module/csvmap"
)
func main() {
// Sample CSV data
csvData := `k1,k2,k3,k4
a1,b1,c1,d1
a2,b2,c2,d2`
// Parse CSV to maps
maps, err := csvmap.ParseCSVStringToMaps(csvData)
if err != nil {
log.Fatal(err)
}
// Print the result
for i, m := range maps {
fmt.Printf("Row %d: %+v\n", i+1, m)
}
// Convert back to CSV
csvString, err := csvmap.MapsToCSVString(maps)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Generated CSV:\n%s\n", csvString)
}
type CSVMapper struct {
Delimiter rune // Field delimiter (default: ',')
Comment rune // Comment character (default: '#')
SkipEmptyLines bool // Whether to skip empty lines (default: true)
}
func NewCSVMapper() *CSVMapper
Creates a new CSVMapper with default settings.
func (c *CSVMapper) ParseCSVToMaps(reader io.Reader) ([]map[string]interface{}, error)
Converts CSV data from an io.Reader to a slice of maps.
func (c *CSVMapper) ParseCSVStringToMaps(csvData string) ([]map[string]interface{}, error)
Converts CSV string data to a slice of maps.
func (c *CSVMapper) MapsToCSV(data []map[string]interface{}, writer io.Writer) error
Converts a slice of maps to CSV format and writes to an io.Writer.
func (c *CSVMapper) MapsToCSVString(data []map[string]interface{}) (string, error)
Converts a slice of maps to CSV format and returns as a string.
For common use cases, the library provides convenience functions that use default settings:
func ParseCSVToMaps(reader io.Reader) ([]map[string]interface