diff --git a/flatten.go b/flatten.go index d7c09da..5b95df7 100644 --- a/flatten.go +++ b/flatten.go @@ -88,7 +88,7 @@ func FlattenString(nestedstr, prefix string, style SeparatorStyle) (string, erro func flatten(top bool, flatMap map[string]interface{}, nested interface{}, prefix string, style SeparatorStyle) error { assign := func(newKey string, v interface{}) error { switch v.(type) { - case map[string]interface{}, []interface{}: + case map[string]interface{}, []map[string]interface{}, []interface{}: if err := flatten(false, flatMap, v, newKey, style); err != nil { return err } @@ -105,6 +105,11 @@ func flatten(top bool, flatMap map[string]interface{}, nested interface{}, prefi newKey := enkey(top, prefix, k, style) assign(newKey, v) } + case []map[string]interface{}: + for i, v := range nested.([]map[string]interface{}) { + newKey := enkey(top, prefix, strconv.Itoa(i), style) + assign(newKey, v) + } case []interface{}: for i, v := range nested.([]interface{}) { newKey := enkey(top, prefix, strconv.Itoa(i), style) diff --git a/flatten_test.go b/flatten_test.go index f81ebb6..92d3ce2 100644 --- a/flatten_test.go +++ b/flatten_test.go @@ -10,7 +10,7 @@ import ( func TestFlatten(t *testing.T) { cases := []struct { - test string + test interface{} want map[string]interface{} prefix string style SeparatorStyle @@ -156,15 +156,35 @@ func TestFlatten(t *testing.T) { "", UnderscoreStyle, }, + { + map[string]interface{}{ + "environments": []map[string]interface{}{{ + "dev": []map[string]interface{}{{ + "spacestation": "abcdefg", + }}, + }}}, + map[string]interface{}{ + "environments.0.dev.0.spacestation": "abcdefg", + }, + "", + DotStyle, + }, } for i, test := range cases { var m interface{} - err := json.Unmarshal([]byte(test.test), &m) - if err != nil { - t.Errorf("%d: failed to unmarshal test: %v", i+1, err) - continue + + switch test.test.(type) { + case string: + err := json.Unmarshal([]byte(test.test.(string)), &m) + if err != nil { + t.Errorf("%d: failed to unmarshal test: %v", i+1, err) + continue + } + default: + m = test.test } + got, err := Flatten(m.(map[string]interface{}), test.prefix, test.style) if err != nil { t.Errorf("%d: failed to flatten: %v", i+1, err)