diff --git a/structs.go b/structs.go index b051c25..00a778e 100644 --- a/structs.go +++ b/structs.go @@ -76,7 +76,8 @@ func (s *Struct) Map() map[string]interface{} { name = tagName } - // if the value is a zero value do not include + // if the value is a zero value and the field is marked as omitempty do + // not include if tagOpts.Has("omitempty") { zero := reflect.Zero(val.Type()).Interface() current := val.Interface() diff --git a/structs_test.go b/structs_test.go index 5d7f04d..8ece554 100644 --- a/structs_test.go +++ b/structs_test.go @@ -148,6 +148,27 @@ func TestMap_CustomTag(t *testing.T) { } +func TestMap_OmitEmpty(t *testing.T) { + type A struct { + Name string + Value string `structs:",omitempty"` + Time time.Time `structs:",omitempty"` + } + a := A{} + + m := Map(a) + + _, ok := m["Value"].(map[string]interface{}) + if ok { + t.Error("Map should not contain the Value field that is tagged as omitempty") + } + + _, ok = m["Time"].(map[string]interface{}) + if ok { + t.Error("Map should not contain the Time field that is tagged as omitempty") + } +} + func TestMap_OmitNested(t *testing.T) { type A struct { Name string