-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap.go
93 lines (82 loc) · 2.32 KB
/
map.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
89
90
91
92
93
package convert
import (
"reflect"
)
// 把map转成map[string]interface{},key的值使用MustString计算。
// 如果子项中也有map,则继续递归执行直到全部转换为map[string]interface{}
// 如果子项有[]interface{},则要继续判定slice的元素中的类型
// 常用于各种xml\yaml\json转换为map的结果的统一处理。
func MustMapStringInterfaceRecursions(leafMap interface{}) map[string]interface{} {
leafType := reflect.TypeOf(leafMap)
if leafType.Kind() != reflect.Map {
return nil
}
leafValue := reflect.ValueOf(leafMap)
if leafValue.Len() == 0 {
return nil
}
resMap := make(map[string]interface{})
leafKeyValues := leafValue.MapKeys()
// key的value
for _, leafKeyValue := range leafKeyValues {
// node的value
nodeValue := leafValue.MapIndex(leafKeyValue)
// 获得实际的key和node
k := leafKeyValue.Interface()
node := nodeValue.Interface()
if nodeValue.IsNil() {
continue
}
strKey := MustString(k)
nodeType := reflect.TypeOf(node)
switch nodeType.Kind() {
case reflect.Map:
temp := MustMapStringInterfaceRecursions(node)
if temp != nil {
resMap[strKey] = temp
}
case reflect.Slice, reflect.Array:
temp := MustMapStringInterfaceRecursionsInArrayInterface(node)
if temp != nil {
resMap[strKey] = temp
}
default:
resMap[strKey] = node
}
}
return resMap
}
// 协助处理[]interface{}中的map[interface{}]interface{}为map[string]interface{}
func MustMapStringInterfaceRecursionsInArrayInterface(leafAry interface{}) []interface{} {
leafType := reflect.TypeOf(leafAry)
if leafType.Kind() != reflect.Array &&
leafType.Kind() != reflect.Slice {
return nil
}
leafValue := reflect.ValueOf(leafAry)
if leafValue.Len() == 0 {
return nil
}
resAry := make([]interface{}, 0)
for i := 0; i < leafValue.Len(); i++ {
nodeValue := leafValue.Index(i)
// 获得实际的key和node
node := nodeValue.Interface()
nodeType := reflect.TypeOf(node)
switch nodeType.Kind() {
case reflect.Array, reflect.Slice:
temp := MustMapStringInterfaceRecursionsInArrayInterface(node)
if temp != nil {
resAry = append(resAry, temp)
}
case reflect.Map:
temp := MustMapStringInterfaceRecursions(node)
if temp != nil {
resAry = append(resAry, temp)
}
default:
resAry = append(resAry, node)
}
}
return resAry
}