-
Notifications
You must be signed in to change notification settings - Fork 3
/
map.go
44 lines (39 loc) · 868 Bytes
/
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
package junocfg
import (
"fmt"
"reflect"
)
func setValue(src map[string]interface{}, path []string, value interface{}) error {
ptr := src
for i, key := range path {
//fmt.Printf("%d %v\n", i, key)
v, ok := ptr[key]
if !ok {
ptr[key] = map[string]interface{}{}
v, ok = ptr[key]
}
if i != len(path)-1 {
value := reflect.ValueOf(v)
if value.Kind() != reflect.Map {
ptr[key] = map[string]interface{}{}
}
if ptr, ok = ptr[key].(map[string]interface{}); !ok {
return fmt.Errorf("setValue error: %v", key)
}
continue
}
ptr[key] = value
break
}
return nil
}
func Items2Map(items ItemArray) (map[string]interface{}, error) {
dst := map[string]interface{}{}
for _, i := range items {
if err := setValue(dst, i.path, i.value); err != nil {
return nil, err
}
}
result := deinterface(dst)
return result, nil
}