gocarina / gocsv

The GoCSV package aims to provide easy CSV serialization and deserialization to the golang programming language
MIT License
1.99k stars 245 forks source link

Implement mapping functions #275

Open kubakl opened 7 months ago

kubakl commented 7 months ago

I would like to have a clean way of sanitising my csvs before the unmarshaling happens. Take this csv as an example:

Name,Age,Height
John,10,1.80
Jack,20,N/A

In this case it will fail to decode due to N/A value. I would like to have a way to replace it with NaN or an empty string so it's omitted. The solution from csvutil package is a really easy and clean one.

    dec, err := csvutil.NewDecoder(r)
    if err != nil {
        log.Fatal(err)
    }

    dec.Map = func(field, column string, v any) string {
        if _, ok := v.(float64); ok && field == "n/a" {
            return "NaN"
        }
        return field
    }