forked from doublerebel/bellows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatten.go
88 lines (82 loc) · 1.9 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package bellows
import (
"fmt"
"reflect"
)
func Flatten(value interface{}, opts ...option) map[string]interface{} {
options := &bellowsOptions{
prefix: "",
sep: ".",
}
for _, opt := range opts {
opt(options)
}
m := make(map[string]interface{}, 5)
FlattenPrefixedToResult(value, options, m)
return m
}
func FlattenPrefixedToResult(value interface{}, opts *bellowsOptions, m map[string]interface{}) {
original := reflect.ValueOf(value)
kind := original.Kind()
if kind == reflect.Ptr || kind == reflect.Interface {
original = reflect.Indirect(original)
kind = original.Kind()
}
if !original.IsValid() {
if opts.prefix != "" {
m[opts.prefix] = nil
}
return
}
t := original.Type()
switch kind {
case reflect.Map:
if t.Key().Kind() != reflect.String {
break
}
keys := original.MapKeys()
base := ""
if opts.prefix != "" {
base = opts.prefix + opts.sep
}
for _, childKey := range keys {
childValue := original.MapIndex(childKey)
FlattenPrefixedToResult(childValue.Interface(), &bellowsOptions{
prefix: base + childKey.String(),
sep: opts.sep,
}, m)
}
case reflect.Struct:
numField := original.NumField()
base := ""
for i := 0; i < numField; i++ {
childValue := original.Field(i)
f := t.Field(i)
childKey := f.Name
if f.Anonymous {
childKey = ""
base = opts.prefix
} else if opts.prefix != "" {
base = opts.prefix + opts.sep
}
FlattenPrefixedToResult(childValue.Interface(), &bellowsOptions{
prefix: base + childKey,
sep: opts.sep,
}, m)
}
case reflect.Array, reflect.Slice:
l := original.Len()
base := opts.prefix
for i := 0; i < l; i++ {
childValue := original.Index(i)
FlattenPrefixedToResult(childValue.Interface(), &bellowsOptions{
prefix: fmt.Sprintf("%s%s[%d]", base, opts.sep, i),
sep: opts.sep,
}, m)
}
default:
if opts.prefix != "" {
m[opts.prefix] = value
}
}
}