Merge pull request #281 from semrekkers/issue-238
Fix empty keyName when decoding struct -> map with omitempty
Mitchell Hashimoto authored 2 years ago
GitHub committed 2 years ago
956 | 956 |
return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
|
957 | 957 |
}
|
958 | 958 |
}
|
959 | |
keyName = tagValue[:index]
|
|
959 |
if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" {
|
|
960 |
keyName = keyNameTagValue
|
|
961 |
}
|
960 | 962 |
} else if len(tagValue) > 0 {
|
961 | 963 |
if tagValue == "-" {
|
962 | 964 |
continue
|
0 | 0 |
package mapstructure
|
1 | 1 |
|
2 | 2 |
import (
|
|
3 |
"fmt"
|
3 | 4 |
"reflect"
|
4 | 5 |
"testing"
|
5 | 6 |
"time"
|
|
600 | 601 |
t.Fatal("expected false")
|
601 | 602 |
}
|
602 | 603 |
}
|
|
604 |
|
|
605 |
// GH-238: Empty key name when decoding map from struct with only omitempty flag
|
|
606 |
func TestMapOmitEmptyWithEmptyFieldnameInTag(t *testing.T) {
|
|
607 |
type Struct struct {
|
|
608 |
Username string `mapstructure:",omitempty"`
|
|
609 |
Age int `mapstructure:",omitempty"`
|
|
610 |
}
|
|
611 |
|
|
612 |
s := Struct{
|
|
613 |
Username: "Joe",
|
|
614 |
}
|
|
615 |
var m map[string]interface{}
|
|
616 |
|
|
617 |
if err := Decode(s, &m); err != nil {
|
|
618 |
t.Fatal(err)
|
|
619 |
}
|
|
620 |
|
|
621 |
expect := "map[Username:Joe]"
|
|
622 |
if got := fmt.Sprintf("%+v", m); expect != got {
|
|
623 |
t.Fatalf("expect %q, got: %s", expect, got)
|
|
624 |
}
|
|
625 |
}
|