-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathappend.go
More file actions
49 lines (41 loc) · 1.34 KB
/
Copy pathappend.go
File metadata and controls
49 lines (41 loc) · 1.34 KB
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
package jsonparser
// Append adds value to the end of the JSON array addressed by keys.
//
// When keys is empty, Append addresses the top-level value. If a keyed path
// does not exist, Append creates it as a single-element array using Set's
// auto-vivification behavior.
//
// SYS-REQ-009, SYS-REQ-110
func Append(data []byte, value []byte, keys ...string) ([]byte, error) {
_, dataType, startOffset, endOffset, err := internalGet(data, keys...)
if err != nil {
if err != KeyPathNotFoundError || len(keys) == 0 {
return nil, err
}
arrayValue := make([]byte, len(value)+2)
offset := WriteToBuffer(arrayValue, "[")
offset += copy(arrayValue[offset:], value)
WriteToBuffer(arrayValue[offset:], "]")
return Set(data, arrayValue, keys...)
}
if dataType != Array {
return nil, MalformedArrayError
}
closeOffset := endOffset - 1
if closeOffset <= startOffset || closeOffset >= len(data) || data[closeOffset] != ']' {
return nil, MalformedArrayError
}
hasElements := nextToken(data[startOffset+1:closeOffset]) != -1
extraSpace := len(value)
if hasElements {
extraSpace++
}
result := make([]byte, len(data)+extraSpace)
offset := copy(result, data[:closeOffset])
if hasElements {
offset += WriteToBuffer(result[offset:], ",")
}
offset += copy(result[offset:], value)
copy(result[offset:], data[closeOffset:])
return result, nil
}