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

Function Set

parser.go:1018–1147  ·  view source on GitHub ↗

* Set - Receives existing data structure, path to set, and data to set at that key. Returns: `value` - modified byte array `err` - On any parsing error */ SYS-REQ-009, SYS-REQ-051, SYS-REQ-068, SYS-REQ-069, SYS-REQ-070, SYS-REQ-110

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

Source from the content-addressed store, hash-verified

1016*/
1017// SYS-REQ-009, SYS-REQ-051, SYS-REQ-068, SYS-REQ-069, SYS-REQ-070, SYS-REQ-110
1018func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) {
1019 // ensure keys are set
1020 if len(keys) == 0 {
1021 return nil, KeyPathNotFoundError
1022 }
1023
1024 _, _, startOffset, endOffset, err := internalGet(data, keys...)
1025 if err != nil {
1026 if err != KeyPathNotFoundError {
1027 // problem parsing the data
1028 return nil, err
1029 }
1030 // full path doesnt exist
1031 // does any subpath exist?
1032 var depth int
1033 for i := range keys {
1034 _, _, start, end, sErr := internalGet(data, keys[:i+1]...)
1035 if sErr != nil {
1036 break
1037 } else {
1038 endOffset = end
1039 startOffset = start
1040 depth++
1041 }
1042 }
1043 comma := true
1044 object := false
1045 // KI-3: when the path's next component expects one container type but
1046 // the existing structure is the other (array-index [N] under an object,
1047 // or an object key under an array), auto-coerce the container to the
1048 // type expected by the path and proceed with fresh insertion. The
1049 // mismatched container is treated as if it needs to be (re)created, so
1050 // the output is always valid JSON.
1051 coerceTopLevel := false
1052 coerceStart := 0
1053 if endOffset == -1 {
1054 firstToken := nextToken(data)
1055 if firstToken < 0 {
1056 return nil, KeyPathNotFoundError
1057 }
1058 pathIsIndex := len(keys[0]) > 0 && keys[0][0] == '['
1059 // An empty trailing key component is the degenerate "no path
1060 // provided" case (SYS-REQ-111), not a real object key — it must
1061 // keep returning KeyPathNotFoundError on a non-object root, so it
1062 // is excluded from auto-coerce.
1063 pathIsObjectKey := len(keys[0]) > 0 && !pathIsIndex
1064 dataIsObject := data[firstToken] == '{'
1065 dataIsArray := data[firstToken] == '['
1066 if (pathIsIndex && dataIsObject) || (pathIsObjectKey && dataIsArray) {
1067 // SYS-REQ-009: cross-type Set at the top level — replace the
1068 // mismatched container with a fresh container of the type the
1069 // path expects, then perform a fresh insertion.
1070 coerceTopLevel = true
1071 coerceStart = firstToken
1072 comma = false
1073 object = !pathIsIndex
1074 endOffset = lastToken(data)
1075 } else if !dataIsObject {

Calls 4

internalGetFunction · 0.85
nextTokenFunction · 0.85
lastTokenFunction · 0.85
createInsertComponentFunction · 0.85