-
Notifications
You must be signed in to change notification settings - Fork 0
/
unstructured_field.go
258 lines (235 loc) · 7.6 KB
/
unstructured_field.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package structemplate
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
)
func ParseKeyPath(keyPath string) []string {
t1 := strings.Trim(keyPath, "$")
t1 = strings.Trim(t1, ".")
return strings.Split(t1, ".")
}
// GetValueOfNestedField gets the value of field specified by `jsonPath` from the target object.
func GetValueOfNestedField(object map[string]interface{}, jsonPath string) (interface{}, error) {
if len(jsonPath) < 1 || jsonPath == "." {
return DeepCopyJSONValue(object), nil
}
paths := ParseKeyPath(jsonPath)
var field interface{} = DeepCopyJSONValue(object)
var tracedPath string = ""
for i := 0; i < len(paths); i++ {
key := paths[i]
tracedPath += "." + key
switch reflect.TypeOf(field).Kind() {
case reflect.Slice:
idx, err := ParseJsonPathArrayIndex(key)
if err != nil {
return nil, errors.Wrap(err, "cannot parse the index of array field: "+tracedPath)
}
tmpField := field.([]interface{})
if len(tmpField) <= int(idx) {
return nil, errors.New(fmt.Sprintf("array field index out of bounds: %d of %s", idx, tracedPath))
}
field = tmpField[idx]
case reflect.Map:
tmpField := field.(map[string]interface{})
field = tmpField[key]
default:
return nil, errors.New("field does not exist: " + tracedPath)
}
}
return field, nil
}
// SetNestedField sets a value in the structure of object
// @Param appendArray: the element to operating is an array and the value should be appended in the array
// @Param value: the value to inject. When append array is true, and value is an array, the elements in `value` will all be appended to the template.
func SetNestedField(object map[string]interface{}, jsonPath string, value interface{}, appendArray bool) error {
if jsonPath == "" {
return errors.New("param jsonPath is empty")
}
paths := ParseKeyPath(jsonPath)
var jumper interface{} = object
var jumperBackNode interface{} = object
// finding the node before last key
for i := 0; i < len(paths)-1; i++ {
currentKey := paths[i]
if len(currentKey) < 1 {
// ignore empty slots
continue
}
switch reflect.TypeOf(jumper).Kind() {
case reflect.Slice:
idx, err := ParseJsonPathArrayIndex(currentKey)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("arror parse array index: %s", currentKey))
}
jumperHolder := jumper.([]interface{})
if int(idx) >= len(jumperHolder) {
return fmt.Errorf("array index out of bounds: %s", currentKey)
}
if jumperHolder[idx] == nil {
jumperHolder[idx] = make(map[string]interface{})
}
jumperBackNode = jumper
jumper = jumperHolder[idx]
case reflect.Map:
jumperBackNode = jumper
jumperHolder := jumper.(map[string]interface{})
nextJumper, ok := jumperHolder[currentKey]
if !ok {
// Auto create missing nodes
nextKey := paths[i+1]
idx, err := ParseJsonPathArrayIndex(nextKey)
if err == nil && idx > -1 {
// 1. .missing_property.[idx]; add an array element
jumperHolder[currentKey] = make([]interface{}, idx+1)
} else {
// 2. .missing_property.other_property; add an object element
jumperHolder[currentKey] = make(map[string]interface{})
} //if: end processing missing nodes
jumper = jumperHolder[currentKey]
} else {
// jump to next node
jumper = nextJumper
}
default:
return fmt.Errorf("element cannot be indexed: %s", currentKey)
}
} // end finding last node
// processing last key and set the value
lastKey := paths[len(paths)-1]
// when append array is set, the jumper must be a map
if appendArray {
jumperObj, ok := jumper.(map[string]interface{})
if !ok {
return fmt.Errorf("append array failed because the node before last node is not an object")
}
if jumperObj[lastKey] == nil {
jumperObj[lastKey] = make([]interface{}, 0)
}
lastNodeType := reflect.TypeOf(jumperObj[lastKey]).Kind()
if lastNodeType != reflect.Slice {
return fmt.Errorf("append array failed because last node is not an array: %s", lastNodeType.String())
}
targetArr := jumperObj[lastKey].([]interface{})
switch reflect.TypeOf(value).Kind() {
case reflect.Slice:
sliceValue := reflect.ValueOf(value)
newSlice := jumperObj[lastKey].([]interface{})
for i := 0; i < sliceValue.Len(); i++ {
newSlice = append(newSlice, sliceValue.Index(i).Interface())
}
jumperObj[lastKey] = newSlice
default:
jumperObj[lastKey] = append(targetArr, value)
}
return nil
}
// set last node
jumperType := reflect.TypeOf(jumper).Kind()
if jumperType == reflect.Slice {
// 1. fixed index array
idx, err := ParseJsonPathArrayIndex(lastKey)
if err != nil {
return fmt.Errorf("cannot set object property inside an array")
}
jumperArray := jumper.([]interface{})
backNode := jumperBackNode.(map[string]interface{})
if len(jumperArray) < int(idx+1) {
return fmt.Errorf("cannot modify the target array: index out of bounds: %s", lastKey)
}
jumperArray[idx] = value
backNode[paths[len(paths)-2]] = jumperArray
return nil
}
// 2. normal object
jumberObj, ok := jumper.(map[string]interface{})
if !ok {
return fmt.Errorf("element cannot be indexed: %s", strings.Join(paths[0:len(paths)-1], "."))
}
jumberObj[lastKey] = value
return nil
}
func ParseJsonPathArrayIndex(idxExp string) (int64, error) {
matched, err := regexp.Match("^\\[\\d+\\]$", []byte(idxExp))
if !matched {
return -1, errors.New("parse index expression failed")
}
if err != nil {
return -1, errors.Wrap(err, "parse index expression failed")
}
idx := strings.TrimLeft(idxExp, "[")
idx = strings.TrimRight(idx, "]")
idxNum, err := strconv.Atoi(idx)
if err != nil {
return -1, errors.Wrap(err, "illegal index number: "+idx)
}
if idxNum < 0 {
return -1, errors.New("index less than 0")
}
return int64(idxNum), nil
}
// DeepCopyJSONValue deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal() and also int64.
// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil
func deepCopyJSONValuebackup(x interface{}) interface{} {
switch x := x.(type) {
case map[string]interface{}:
if x == nil {
// Typed nil - an interface{} that contains a type map[string]interface{} with a value of nil
return x
}
clone := make(map[string]interface{}, len(x))
for k, v := range x {
clone[k] = DeepCopyJSONValue(v)
}
return clone
case []interface{}:
if x == nil {
// Typed nil - an interface{} that contains a type []interface{} with a value of nil
return x
}
clone := make([]interface{}, len(x))
for i, v := range x {
clone[i] = DeepCopyJSONValue(v)
}
return clone
case string, int64, int32, int16, int8, int, bool, float64, float32, nil: // rune is int32
return x
default:
panic(fmt.Errorf("cannot deep copy %T", x))
}
}
func DeepCopyJSONValue(x interface{}) interface{} {
val := reflect.ValueOf(x)
switch val.Kind() {
case reflect.Map:
if val.IsNil() {
return x
}
clone := reflect.MakeMap(val.Type())
for _, k := range val.MapKeys() {
clone.SetMapIndex(k, reflect.ValueOf(DeepCopyJSONValue(val.MapIndex(k).Interface())))
}
return clone.Interface()
case reflect.Slice:
if val.IsNil() {
return x
}
clone := reflect.MakeSlice(val.Type(), val.Len(), val.Cap())
for i := 0; i < val.Len(); i++ {
clone.Index(i).Set(reflect.ValueOf(DeepCopyJSONValue(val.Index(i).Interface())))
}
return clone.Interface()
case reflect.String, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int, reflect.Bool, reflect.Float64, reflect.Float32:
return x
default:
if val.IsValid() && val.CanInterface() {
return x
}
panic(fmt.Errorf("cannot deep copy %T", x))
}
}