-
Notifications
You must be signed in to change notification settings - Fork 1
/
gflatten.go
72 lines (62 loc) · 1.48 KB
/
gflatten.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
package gflatten
import "reflect"
var WRAP = struct {
SQUARE_BRACKET string
SINGLE_QUOTE string
DOUBLE_QUOTE string
BACKTICK string
NONE string
}{
SQUARE_BRACKET: "[]",
SINGLE_QUOTE: "'",
DOUBLE_QUOTE: "\"",
BACKTICK: "`",
NONE: "",
}
type Option struct {
ParameterDelimiter string
ArrayDelimiter string
Prefix string
ParameterWrap string
ArrayWrap string
}
func Flatten(src any, option Option) (map[string]any, error) {
dest := make(map[string]any)
mapSrc, err := toMap(src)
if err != nil {
return dest, err
}
flatten(option.Prefix, mapSrc, dest, option)
return dest, nil
}
func flatten(prefix string, src map[string]any, dest map[string]any, option Option) {
for k, v := range src {
switch reflect.TypeOf(v).Kind() {
case reflect.Slice:
flattenArray(prefix, k, v, dest, option)
case reflect.Map:
flatten(
parameterWrap(prefix, k, option),
v.(map[string]any),
dest,
option,
)
default:
dest[parameterWrap(prefix, k, option)] = v
}
}
}
func flattenArray(prefix string, key string, value any, dest map[string]any, option Option) {
for i := 0; i < len(value.([]any)); i++ {
if _, ok := value.([]any)[i].(map[string]any); ok {
flatten(
arrayWrap(parameterWrap(prefix, key, option), i, option),
value.([]any)[i].(map[string]any),
dest,
option,
)
} else {
dest[arrayWrap(parameterWrap(prefix, key, option), i, option)] = value.([]any)[i]
}
}
}