From 1838bce50f467712b110876952ab1831f48230a3 Mon Sep 17 00:00:00 2001 From: Dumindu Madithiyagasthenna Date: Tue, 6 Jul 2021 14:28:26 +1000 Subject: [PATCH 1/2] Added test for non-struct slices --- map_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/map_test.go b/map_test.go index 8085b7e..3eb75c0 100644 --- a/map_test.go +++ b/map_test.go @@ -28,6 +28,7 @@ type Example struct { ObjThree ObjTwo `custom:"-"` // explicitly ignored Id int `custom:"id"` Call int `custom:"data.call"` + Array []string `custom:"array"` ArrayObj []ObjThree `custom:"list"` //three int `custom:"three"` // unexported, TODO: handle panic } @@ -49,8 +50,9 @@ func TestFullStructToMap(t *testing.T) { Hello: "1", Text: "2", }, - Id: 01, - Call: 02, + Id: 01, + Call: 02, + Array: []string{"1", "2"}, ArrayObj: []ObjThree{ {"hi", 1}, {"world", 2}, @@ -74,6 +76,7 @@ func TestFullStructToMap(t *testing.T) { "call": 2 }, "id": 1, + "array": ["1", "2"], "list": [ { "name": "hi", From 723272633808762786fd3b6e649d358d9b767ca2 Mon Sep 17 00:00:00 2001 From: Dumindu Madithiyagasthenna Date: Tue, 6 Jul 2021 14:28:34 +1000 Subject: [PATCH 2/2] Fixed panics for non-struct slices --- map.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/map.go b/map.go index 3240435..42da414 100644 --- a/map.go +++ b/map.go @@ -93,18 +93,22 @@ func getMapOfAllKeyValues(s interface{}) *map[string]interface{} { switch reflect.TypeOf(v).Kind() { // if any of them is a slice case reflect.Slice: - var sliceOfMap []map[string]interface{} - s := reflect.ValueOf(v) - // iterate through the slice - for i := 0; i < s.Len(); i++ { - if s.Index(i).CanInterface() { - m := getMapOfAllKeyValues(s.Index(i).Interface()) // get the map value of the object, recursively - if m != nil { - sliceOfMap = append(sliceOfMap, *m) // append to the slice + if reflect.TypeOf(v).Elem().Kind() == reflect.Struct{ + var sliceOfMap []map[string]interface{} + s := reflect.ValueOf(v) + // iterate through the slice + for i := 0; i < s.Len(); i++ { + if s.Index(i).CanInterface() { + m := getMapOfAllKeyValues(s.Index(i).Interface()) // get the map value of the object, recursively + if m != nil { + sliceOfMap = append(sliceOfMap, *m) // append to the slice + } } } + finalMap[k] = sliceOfMap + } else { + finalMap[k] = v } - finalMap[k] = sliceOfMap default: finalMap[k] = v }