Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion flatten.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
Expand Down
30 changes: 25 additions & 5 deletions flatten_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func TestFlatten(t *testing.T) {
cases := []struct {
test string
test interface{}
want map[string]interface{}
prefix string
style SeparatorStyle
Expand Down Expand Up @@ -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)
Expand Down