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
8 changes: 8 additions & 0 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -1681,6 +1681,14 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
continue
}

// Skip keys already consumed by another field's exact
// match, so a case-insensitive fallback can't claim the
// same key a second time (e.g. fields `Name` and `NAME`
// both matching the key "name").
if _, unused := dataValKeysUnused[dataValKey.Interface()]; !unused {
continue
}

if d.config.MatchName(mK, fieldName) {
rawMapKey = dataValKey
rawMapVal = dataVal.MapIndex(dataValKey)
Expand Down
22 changes: 22 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4673,3 +4673,25 @@ func TestUnmarshaler_StructToMap(t *testing.T) {
t.Errorf("expected Age 30, got %v", result["Age"])
}
}

func TestDecode_caseInsensitiveDuplicateKey(t *testing.T) {
// A case-insensitive fallback must not claim a key that another field
// already matched exactly: decoding {"name": ...} into a struct with both
// `name` and `NAME` fields should populate only the exact match.
type Result struct {
Name string `mapstructure:"name"`
NAME string `mapstructure:"NAME"`
}

var result Result
if err := Decode(map[string]interface{}{"name": "lower"}, &result); err != nil {
t.Fatalf("got an err: %s", err)
}

if result.Name != "lower" {
t.Errorf("Name should be 'lower', got: %#v", result.Name)
}
if result.NAME != "" {
t.Errorf("NAME should be empty, got: %#v", result.NAME)
}
}