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

Commit

Permalink
Merge pull request #281 from semrekkers/issue-238
Browse files Browse the repository at this point in the history
Fix empty keyName when decoding struct -> map with omitempty
  • Loading branch information
mitchellh authored Apr 20, 2022
2 parents 74e07d1 + eb645e2 commit 5a2eb61
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion mapstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,7 +957,9 @@ func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val re
return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
}
}
keyName = tagValue[:index]
if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" {
keyName = keyNameTagValue
}
} else if len(tagValue) > 0 {
if tagValue == "-" {
continue
Expand Down
23 changes: 23 additions & 0 deletions mapstructure_bugs_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mapstructure

import (
"fmt"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -601,3 +602,25 @@ func TestMapSquash(t *testing.T) {
t.Fatal("expected false")
}
}

// GH-238: Empty key name when decoding map from struct with only omitempty flag
func TestMapOmitEmptyWithEmptyFieldnameInTag(t *testing.T) {
type Struct struct {
Username string `mapstructure:",omitempty"`
Age int `mapstructure:",omitempty"`
}

s := Struct{
Username: "Joe",
}
var m map[string]interface{}

if err := Decode(s, &m); err != nil {
t.Fatal(err)
}

expect := "map[Username:Joe]"
if got := fmt.Sprintf("%+v", m); expect != got {
t.Fatalf("expect %q, got: %s", expect, got)
}
}

0 comments on commit 5a2eb61

Please sign in to comment.