jszwec / csvutil

csvutil provides fast and idiomatic mapping between CSV and Go (golang) values.
MIT License
944 stars 63 forks source link

cannot unmarshal "" into Go value of type int #67

Closed mayeter closed 10 months ago

mayeter commented 10 months ago

Hello, I have a CSV file which has some optional fields. Unmarshal method gives me this error if any non-string field is empty. It works perfectly when all fields are filled or empty fields are corresponding to a string value.

Here is what my csv file looks like:

record_name,zone_name,location,record_type,record_value,ttl,proxy_enabled,proxy_value
test-record,example.com,usa,A,1.1.1.1,,,
test-record2,example.com,usa,CNAME,test-record.example.com,60,,
test-record3,example.com,usa,,10.10.10.10,,true,2.2.2.2

And my go struct:

type CSVReaderForRecords struct {
    RecordName   string `csv:"record_name"`
    ZoneName     string `csv:"zone_name"`
    RecordType   string `csv:"record_type"`
    RecordValue  string `csv:"record_value"`
    TTL          int `csv:"ttl"`
    ProxyEnabled bool   `csv:"proxy_enabled"`
    ProxyValue   string `csv:"proxy_value"`
    Location     string `csv:"location"`
}

It also gives non-existinf column numbers in the error:

csvutil: cannot unmarshal "" into Go value of type int: field "ttl" line 2 column 39

or

csvutil: cannot unmarshal "" into Go value of type bool: field "proxy_enabled" line 2 column 42

I can work around of this by converting my optional fields' types to string and convert them with strconv, but it would be nice if Unmarshall would handle it.

Thanks, great work by the way

jszwec commented 10 months ago

This is supported, please read the documentation and examples before creating the issue

look up omitempty tag here: https://pkg.go.dev/github.com/jszwec/csvutil#Decoder.Decode and here https://github.com/jszwec/csvutil?tab=readme-ov-file#examples_unmarshal

mayeter commented 10 months ago

Thank you very much, this solves my problem. Interesting that I never noticed that tag, I actually reviewed it a couple times.