MCPcopy Create free account
hub / github.com/buger/jsonparser / Append

Function Append

append.go:10–49  ·  view source on GitHub ↗

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

(data []byte, value []byte, keys ...string)

Source from the content-addressed store, hash-verified

8//
9// SYS-REQ-009, SYS-REQ-110
10func Append(data []byte, value []byte, keys ...string) ([]byte, error) {
11 _, dataType, startOffset, endOffset, err := internalGet(data, keys...)
12 if err != nil {
13 if err != KeyPathNotFoundError || len(keys) == 0 {
14 return nil, err
15 }
16
17 arrayValue := make([]byte, len(value)+2)
18 offset := WriteToBuffer(arrayValue, "[")
19 offset += copy(arrayValue[offset:], value)
20 WriteToBuffer(arrayValue[offset:], "]")
21
22 return Set(data, arrayValue, keys...)
23 }
24
25 if dataType != Array {
26 return nil, MalformedArrayError
27 }
28
29 closeOffset := endOffset - 1
30 if closeOffset <= startOffset || closeOffset >= len(data) || data[closeOffset] != ']' {
31 return nil, MalformedArrayError
32 }
33
34 hasElements := nextToken(data[startOffset+1:closeOffset]) != -1
35 extraSpace := len(value)
36 if hasElements {
37 extraSpace++
38 }
39
40 result := make([]byte, len(data)+extraSpace)
41 offset := copy(result, data[:closeOffset])
42 if hasElements {
43 offset += WriteToBuffer(result[offset:], ",")
44 }
45 offset += copy(result[offset:], value)
46 copy(result[offset:], data[closeOffset:])
47
48 return result, nil
49}

Callers 10

TestAppendTopLevelArrayFunction · 0.85
TestAppendEmptyArrayFunction · 0.85
TestAppendNestedArrayFunction · 0.85
TestAppendObjectFunction · 0.85
TestAppendStringFunction · 0.85
TestAppendCreatePathFunction · 0.85
TestAppendNonArrayErrorFunction · 0.85
TestAppendRoundTripFunction · 0.85
TestAppendMultipleFunction · 0.85

Calls 4

internalGetFunction · 0.85
WriteToBufferFunction · 0.85
SetFunction · 0.85
nextTokenFunction · 0.85

Tested by 10

TestAppendTopLevelArrayFunction · 0.68
TestAppendEmptyArrayFunction · 0.68
TestAppendNestedArrayFunction · 0.68
TestAppendObjectFunction · 0.68
TestAppendStringFunction · 0.68
TestAppendCreatePathFunction · 0.68
TestAppendNonArrayErrorFunction · 0.68
TestAppendRoundTripFunction · 0.68
TestAppendMultipleFunction · 0.68