From 87e191fbebe58443964ef780a79a2b071df31396 Mon Sep 17 00:00:00 2001 From: mrekhi Date: Tue, 25 Apr 2023 11:39:09 -0700 Subject: [PATCH] fix: empty map to empty json --- sheriff.go | 2 +- sheriff_test.go | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/sheriff.go b/sheriff.go index 8ce11db..332505c 100644 --- a/sheriff.go +++ b/sheriff.go @@ -248,7 +248,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 d079e4b..6510824 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"` }