-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
105 lines (100 loc) · 2.28 KB
/
convert.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
94
95
96
97
98
99
100
101
102
103
104
105
package convert
import (
"strconv"
"strings"
)
// SliceToMap converts string slice into map that can be encoded into JSON.
func SliceToMap(path []string, value interface{}) map[string]interface{} {
var array bool
var index int
i := strings.Index(path[0], "[")
if i > -1 && len(path[0]) > i+1 {
indexStr := path[0][i+1 : len(path[0])-1]
indexInt, err := strconv.Atoi(indexStr)
if err == nil {
index = indexInt
array = true
path[0] = path[0][:i]
}
}
if len(path) == 1 {
if !array {
return map[string]interface{}{
path[0]: value,
}
}
arr := make([]interface{}, index+1)
arr[index] = value
return map[string]interface{}{
path[0]: arr,
}
}
key := path[0]
path = path[1:]
m := SliceToMap(path, value)
if !array {
return map[string]interface{}{
key: m,
}
}
arr := make([]interface{}, index+1)
arr[index] = m
return map[string]interface{}{
key: arr,
}
}
// MergeJSONWithMap accepts interface (effectively, JSON) and a map and merges them together.
// Source map keys are being overwritten by appendix keys if they overlap.
// nolint:gocyclo
func MergeJSONWithMap(source, appendix interface{}) interface{} {
switch appendixValue := appendix.(type) {
case nil:
return source
case float64, bool, string:
return appendixValue
case []interface{}:
sourceInterface, ok := source.([]interface{})
if !ok {
return appendixValue
}
resArrLen := len(sourceInterface)
if len(appendixValue) > resArrLen {
resArrLen = len(appendixValue)
}
resArr := make([]interface{}, resArrLen)
for i := range resArr {
var a, b interface{}
if i < len(appendixValue) {
b = appendixValue[i]
}
if i < len(sourceInterface) {
a = sourceInterface[i]
}
resArr[i] = MergeJSONWithMap(a, b)
}
source = resArr
case map[string]interface{}:
switch s := source.(type) {
case float64, bool, string:
return appendixValue
case nil:
source = make(map[string]interface{})
return MergeJSONWithMap(source, appendixValue)
case map[string]interface{}:
for k, v := range appendixValue {
if k == "" {
return MergeJSONWithMap(s, v)
}
s[k] = MergeJSONWithMap(s[k], v)
}
source = s
case []interface{}:
for k, v := range appendixValue {
if k == "" {
return MergeJSONWithMap(s, v)
}
}
}
}
return source
}