Skip to content
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

Fix untagged field decoding in case of decode to struct #7

Merged
merged 1 commit into from
Dec 18, 2023
Merged
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
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
Loading