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

Function Set

parser.go:1280–1413  ·  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

1278*/
1279// SYS-REQ-009, SYS-REQ-051, SYS-REQ-068, SYS-REQ-069, SYS-REQ-070, SYS-REQ-110
1280func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) {
1281 // ensure keys are set
1282 if len(keys) == 0 {
1283 return nil, KeyPathNotFoundError
1284 }
1285
1286 _, _, startOffset, endOffset, err := internalGet(data, keys...)
1287 if err != nil {
1288 if err != KeyPathNotFoundError {
1289 // problem parsing the data
1290 return nil, err
1291 }
1292 // full path doesnt exist
1293 // does any subpath exist?
1294 var depth int
1295 for i := range keys {
1296 _, _, start, end, sErr := internalGet(data, keys[:i+1]...)
1297 if sErr != nil {
1298 break
1299 } else {
1300 endOffset = end
1301 startOffset = start
1302 depth++
1303 }
1304 }
1305 comma := true
1306 object := false
1307 // KI-3: when the path's next component expects one container type but
1308 // the existing structure is the other (array-index [N] under an object,
1309 // or an object key under an array), auto-coerce the container to the
1310 // type expected by the path and proceed with fresh insertion. The
1311 // mismatched container is treated as if it needs to be (re)created, so
1312 // the output is always valid JSON.
1313 coerceTopLevel := false
1314 coerceStart := 0
1315 if endOffset == -1 {
1316 firstToken := nextToken(data)
1317 if firstToken < 0 {
1318 return nil, KeyPathNotFoundError
1319 }
1320 pathIsIndex := len(keys[0]) > 0 && keys[0][0] == '['
1321 // An empty trailing key component is the degenerate "no path
1322 // provided" case (SYS-REQ-111), not a real object key — it must
1323 // keep returning KeyPathNotFoundError on a non-object root, so it
1324 // is excluded from auto-coerce.
1325 pathIsObjectKey := len(keys[0]) > 0 && !pathIsIndex
1326 dataIsObject := data[firstToken] == '{'
1327 dataIsArray := data[firstToken] == '['
1328 if (pathIsIndex && dataIsObject) || (pathIsObjectKey && dataIsArray) {
1329 // SYS-REQ-009: cross-type Set at the top level — replace the
1330 // mismatched container with a fresh container of the type the
1331 // path expects, then perform a fresh insertion.
1332 coerceTopLevel = true
1333 coerceStart = firstToken
1334 comma = false
1335 object = !pathIsIndex
1336 endOffset = lastToken(data)
1337 } else if !dataIsObject {

Calls 4

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