From 459725b266ed6692fbe4de71395b41913e337985 Mon Sep 17 00:00:00 2001 From: Mandeep Rekhi Date: Tue, 9 May 2023 04:10:53 -0700 Subject: [PATCH] fix: empty map to empty json (#38) Co-authored-by: mrekhi Co-authored-by: Michael Weibel <307427+mweibel@users.noreply.github.com> --- sheriff.go | 2 +- sheriff_test.go | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/sheriff.go b/sheriff.go index 5d37c51..85ca75b 100644 --- a/sheriff.go +++ b/sheriff.go @@ -263,7 +263,7 @@ func marshalValue(options *Options, v reflect.Value) (interface{}, error) { if k == reflect.Map { mapKeys := v.MapKeys() if len(mapKeys) == 0 { - return nil, nil + return val, nil } if mapKeys[0].Kind() != reflect.String { return nil, MarshalInvalidTypeError{t: mapKeys[0].Kind(), data: val} diff --git a/sheriff_test.go b/sheriff_test.go index 84e438f..cd79294 100644 --- a/sheriff_test.go +++ b/sheriff_test.go @@ -505,13 +505,33 @@ func TestMarshal_EmptyMap(t *testing.T) { assert.NoError(t, err) expected, err := json.Marshal(map[string]interface{}{ - "a_map": nil, + "a_map": make(map[string]interface{}), }) assert.NoError(t, err) assert.Equal(t, string(expected), string(actual)) } +func TestMarshal_EmptyMapJson(t *testing.T) { + emp := EmptyMapTest{ + AMap: make(map[string]string), + } + o := &Options{ + Groups: []string{"test"}, + } + + actualMap, err := Marshal(o, emp) + assert.NoError(t, err) + + actual, err := json.Marshal(actualMap) + assert.NoError(t, err) + + expected, err := json.Marshal(emp) + assert.NoError(t, err) + + assert.Equal(t, string(expected), string(actual)) +} + type TestMarshal_Embedded struct { Foo string `json:"foo" groups:"test"` }