-
Notifications
You must be signed in to change notification settings - Fork 6
/
flatten.go
64 lines (53 loc) · 1.45 KB
/
flatten.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package flatten
import (
"fmt"
"strconv"
)
// Flatten generates a flat map from a nested one. The nested map may include values of type map, slice and scalar, but
// not struct. Keys in the flat map will be a compound of descending map keys and slice iterations.
func Flatten(nested map[string]interface{}) (map[string]interface{}, error) {
flatmap := make(map[string]interface{})
err := flatten(true, flatmap, nested, "")
if err != nil {
return nil, err
}
return flatmap, nil
}
func flatten(top bool, flatMap map[string]interface{}, nested interface{}, prefix string) error {
assign := func(newKey string, v interface{}) error {
switch v.(type) {
case map[string]interface{}, []interface{}:
if err := flatten(false, flatMap, v, newKey); err != nil {
return err
}
default:
flatMap[newKey] = v
}
return nil
}
switch nested.(type) {
case map[string]interface{}:
for k, v := range nested.(map[string]interface{}) {
newKey := enkey(top, prefix, k)
assign(newKey, v)
}
case []interface{}:
for i, v := range nested.([]interface{}) {
newKey := enkey(top, prefix, strconv.Itoa(i))
assign(newKey, v)
}
default:
// Nested input must be a slice or map, for everything else we are returning an error.
return fmt.Errorf("invalid input: must be a map or slice")
}
return nil
}
func enkey(top bool, prefix, subkey string) string {
key := prefix
if top {
key += subkey
} else {
key += "_" + subkey
}
return key
}