Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

Commit 5a2eb61

Browse files
authored
Merge pull request #281 from semrekkers/issue-238
Fix empty keyName when decoding struct -> map with omitempty
2 parents 74e07d1 + eb645e2 commit 5a2eb61

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

mapstructure.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -957,7 +957,9 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re
957957
return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
958958
}
959959
}
960-
keyName = tagValue[:index]
960+
if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" {
961+
keyName = keyNameTagValue
962+
}
961963
} else if len(tagValue) > 0 {
962964
if tagValue == "-" {
963965
continue

mapstructure_bugs_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package mapstructure
22

33
import (
4+
"fmt"
45
"reflect"
56
"testing"
67
"time"
@@ -601,3 +602,25 @@ func TestMapSquash(t *testing.T) {
601602
t.Fatal("expected false")
602603
}
603604
}
605+
606+
// GH-238: Empty key name when decoding map from struct with only omitempty flag
607+
func TestMapOmitEmptyWithEmptyFieldnameInTag(t *testing.T) {
608+
type Struct struct {
609+
Username string `mapstructure:",omitempty"`
610+
Age int `mapstructure:",omitempty"`
611+
}
612+
613+
s := Struct{
614+
Username: "Joe",
615+
}
616+
var m map[string]interface{}
617+
618+
if err := Decode(s, &m); err != nil {
619+
t.Fatal(err)
620+
}
621+
622+
expect := "map[Username:Joe]"
623+
if got := fmt.Sprintf("%+v", m); expect != got {
624+
t.Fatalf("expect %q, got: %s", expect, got)
625+
}
626+
}

0 commit comments

Comments
 (0)