Skip to content

Commit

Permalink
Fix untagged field decoding in case of decode to struct
Browse files Browse the repository at this point in the history
  • Loading branch information
Anton N. Ryabkov committed Jun 9, 2022
1 parent bf980b3 commit 2e2be32
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -1358,6 +1358,9 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
fieldName := field.Name

tagValue := field.Tag.Get(d.config.TagName)
if tagValue == "" && d.config.IgnoreUntaggedFields {
continue
}
tagValue = strings.SplitN(tagValue, ",", 2)[0]
if tagValue != "" {
fieldName = tagValue
Expand Down
38 changes: 38 additions & 0 deletions mapstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2732,6 +2732,44 @@ func TestDecoder_IgnoreUntaggedFields(t *testing.T) {
}
}

func TestDecoder_IgnoreUntaggedFieldsWithStruct(t *testing.T) {
type Output struct {
UntaggedInt int
TaggedNumber int `mapstructure:"tagged_number"`
UntaggedString string
TaggedString string `mapstructure:"tagged_string"`
}
input := map[interface{}]interface{}{
"untaggedint": 31,
"tagged_number": 41,
"untagged_string": "hidden",
"tagged_string": "visible",
}
actual := Output{}
config := &DecoderConfig{
Result: &actual,
IgnoreUntaggedFields: true,
}

decoder, err := NewDecoder(config)
if err != nil {
t.Fatalf("err: %s", err)
}

err = decoder.Decode(input)
if err != nil {
t.Fatalf("err: %s", err)
}

expected := Output{
TaggedNumber: 41,
TaggedString: "visible",
}
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Decode() expected: %#v\ngot: %#v", expected, actual)
}
}

func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
var result Slice
err := Decode(input, &result)
Expand Down

0 comments on commit 2e2be32

Please sign in to comment.