Skip to content

Commit

Permalink
Merge pull request #8 from dumim/develop
Browse files Browse the repository at this point in the history
Fixed panics for non-struct slices
  • Loading branch information
dumim authored Jul 6, 2021
2 parents d6d59b1 + 7232726 commit 59c9118
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
22 changes: 13 additions & 9 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
7 changes: 5 additions & 2 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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},
Expand All @@ -74,6 +76,7 @@ func TestFullStructToMap(t *testing.T) {
"call": 2
},
"id": 1,
"array": ["1", "2"],
"list": [
{
"name": "hi",
Expand Down

0 comments on commit 59c9118

Please # to comment.