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

Function setConfig

parser.go:1346–1479  ·  view source on GitHub ↗

SYS-REQ-115

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

Source from the content-addressed store, hash-verified

1344
1345// SYS-REQ-115
1346func setConfig(config Config, data []byte, setValue []byte, keys ...string) (value []byte, err error) {
1347 // ensure keys are set
1348 if len(keys) == 0 {
1349 return nil, KeyPathNotFoundError
1350 }
1351
1352 _, _, startOffset, endOffset, err := internalGetConfig(config, data, keys...)
1353 if err != nil {
1354 if err != KeyPathNotFoundError {
1355 // problem parsing the data
1356 return nil, err
1357 }
1358 // full path doesnt exist
1359 // does any subpath exist?
1360 var depth int
1361 for i := range keys {
1362 _, _, start, end, sErr := internalGetConfig(config, data, keys[:i+1]...)
1363 if sErr != nil {
1364 break
1365 } else {
1366 endOffset = end
1367 startOffset = start
1368 depth++
1369 }
1370 }
1371 comma := true
1372 object := false
1373 // KI-3: when the path's next component expects one container type but
1374 // the existing structure is the other (array-index [N] under an object,
1375 // or an object key under an array), auto-coerce the container to the
1376 // type expected by the path and proceed with fresh insertion. The
1377 // mismatched container is treated as if it needs to be (re)created, so
1378 // the output is always valid JSON.
1379 coerceTopLevel := false
1380 coerceStart := 0
1381 if endOffset == -1 {
1382 firstToken := nextTokenConfig(config, data)
1383 if firstToken < 0 {
1384 return nil, KeyPathNotFoundError
1385 }
1386 pathIsIndex := len(keys[0]) > 0 && keys[0][0] == '['
1387 // An empty trailing key component is the degenerate "no path
1388 // provided" case (SYS-REQ-111), not a real object key — it must
1389 // keep returning KeyPathNotFoundError on a non-object root, so it
1390 // is excluded from auto-coerce.
1391 pathIsObjectKey := len(keys[0]) > 0 && !pathIsIndex
1392 dataIsObject := data[firstToken] == '{'
1393 dataIsArray := data[firstToken] == '['
1394 if (pathIsIndex && dataIsObject) || (pathIsObjectKey && dataIsArray) {
1395 // SYS-REQ-009: cross-type Set at the top level — replace the
1396 // mismatched container with a fresh container of the type the
1397 // path expects, then perform a fresh insertion.
1398 coerceTopLevel = true
1399 coerceStart = firstToken
1400 comma = false
1401 object = !pathIsIndex
1402 endOffset = lastToken(data)
1403 } else if !dataIsObject {

Callers 2

SetFunction · 0.85
SetMethod · 0.85

Calls 4

internalGetConfigFunction · 0.85
nextTokenConfigFunction · 0.85
lastTokenFunction · 0.85
createInsertComponentFunction · 0.85

Tested by

no test coverage detected