Skip to content

fix quoted headers #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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