From 4d0d8261cce2fc495c48bd8c8a45faf79de4f526 Mon Sep 17 00:00:00 2001 From: Michael Montgomery Date: Tue, 15 Dec 2020 14:17:00 -0600 Subject: [PATCH] Ensure uninitialized map is initialized when unmarshaling json Add tests for this scenario --- slices/map.go | 3 +++ slices/map_test.go | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/slices/map.go b/slices/map.go index d7f58ed4..c99e8a13 100644 --- a/slices/map.go +++ b/slices/map.go @@ -51,6 +51,9 @@ func (m Map) UnmarshalJSON(b []byte) error { if err != nil { return err } + if m == nil { + m = Map{} + } for key, value := range stuff { m[key] = value } diff --git a/slices/map_test.go b/slices/map_test.go index e5d4963b..265d9940 100644 --- a/slices/map_test.go +++ b/slices/map_test.go @@ -24,3 +24,14 @@ func Test_Map_MarshalJSON(t *testing.T) { r.NoError(err) r.Equal([]byte(`{"a":"b"}`), b) } + +func Test_Map_UnMarshalJSON_uninitialized_map_does_not_panic(t *testing.T) { + r := require.New(t) + + maps := make([]Map, 0) + r.NotPanics(func() { + err := json.Unmarshal([]byte(`[{"a": "b"}]`), &maps) + r.NoError(err) + r.Len(maps, 1) + }) +}