Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ func (d *Decoder) Decode(v interface{}) error {
// Decoder state required to map CSV records later on.
func (d *Decoder) DecodeHeader(line string) ([]string, error) {
d.headerKeys = strings.Split(line, string(d.sep))
d.headerKeys = maybeTrimQuotes(d.headerKeys)

if len(d.headerKeys) == 0 {
return nil, fmt.Errorf("csv: empty header")
}
Expand Down Expand Up @@ -560,3 +562,17 @@ func setValue(dst reflect.Value, src, fName string) error {
}
return nil
}

func maybeTrimQuotes(tokens []string) []string {
trimmed := make([]string, 0, len(tokens))
for _, s := range tokens {
if len(s) > 0 && s[0] == '"' {
s = s[1:]
}
if len(s) > 0 && s[len(s)-1] == '"' {
s = s[:len(s)-1]
}
trimmed = append(trimmed, s)
}
return trimmed
}
14 changes: 14 additions & 0 deletions unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ func (x SpecialStruct) String() string {

const (
CsvWithHeader = `s,i,f,b
Hello,42,23.45,true`
CsvWithQuotedHeader = `"s","i","f","b"
Hello,42,23.45,true`
CsvWithoutHeader = `Hello,true,42,23.45`
CsvWhitespace = ` Hello , true , 42 , 23.45`
Expand Down Expand Up @@ -275,6 +277,18 @@ func TestUnmarshalFromByte(t *testing.T) {
CheckA(t, a[0], A1)
}

func TestUnmarshalQuotedFromByte(t *testing.T) {
a := make([]*A, 0)
if err := Unmarshal([]byte(CsvWithQuotedHeader), &a); err != nil {
t.Error(err)
}
if len(a) != 1 {
t.Errorf("invalid record count, got=%d expected=%d", len(a), 1)
return
}
CheckA(t, a[0], A1)
}

func TestUnmarshalFromReader(t *testing.T) {
r := bytes.NewReader([]byte(CsvWithHeader))
dec := NewDecoder(r)
Expand Down