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

Function setConfig

parser.go:1400–1573  ·  view source on GitHub ↗

SYS-REQ-115

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

Source from the content-addressed store, hash-verified

1398
1399// SYS-REQ-115
1400func setConfig(config Config, data []byte, setValue []byte, keys ...string) (value []byte, err error) {
1401 // ensure keys are set
1402 if len(keys) == 0 {
1403 return nil, KeyPathNotFoundError
1404 }
1405
1406 _, _, startOffset, endOffset, err := internalGetConfig(config, data, keys...)
1407 if err != nil {
1408 if err != KeyPathNotFoundError {
1409 // problem parsing the data
1410 return nil, err
1411 }
1412 // full path doesnt exist
1413 // does any subpath exist?
1414 var depth int
1415 for i := range keys {
1416 _, _, start, end, sErr := internalGetConfig(config, data, keys[:i+1]...)
1417 if sErr != nil {
1418 break
1419 } else {
1420 endOffset = end
1421 startOffset = start
1422 depth++
1423 }
1424 }
1425 comma := true
1426 object := false
1427 // KI-3: when the path's next component expects one container type but
1428 // the existing structure is the other (array-index [N] under an object,
1429 // or an object key under an array), auto-coerce the container to the
1430 // type expected by the path and proceed with fresh insertion. The
1431 // mismatched container is treated as if it needs to be (re)created, so
1432 // the output is always valid JSON.
1433 coerceTopLevel := false
1434 coerceStart := 0
1435 topLevelArrayAppend := false
1436 topLevelArrayEmpty := false
1437 topLevelArrayStart := 0
1438 topLevelArrayInsertOffset := 0
1439 if endOffset == -1 {
1440 firstToken := nextTokenConfig(config, data)
1441 if firstToken < 0 {
1442 return nil, KeyPathNotFoundError
1443 }
1444 pathIsIndex := len(keys[0]) > 0 && keys[0][0] == '['
1445 // An empty trailing key component is the degenerate "no path
1446 // provided" case (SYS-REQ-111), not a real object key — it must
1447 // keep returning KeyPathNotFoundError on a non-object root, so it
1448 // is excluded from auto-coerce.
1449 pathIsObjectKey := len(keys[0]) > 0 && !pathIsIndex
1450 dataIsObject := data[firstToken] == '{'
1451 dataIsArray := data[firstToken] == '['
1452 if (pathIsIndex && dataIsObject) || (pathIsObjectKey && dataIsArray) {
1453 // SYS-REQ-009: cross-type Set at the top level — replace the
1454 // mismatched container with a fresh container of the type the
1455 // path expects, then perform a fresh insertion.
1456 coerceTopLevel = true
1457 coerceStart = firstToken

Callers 2

SetFunction · 0.85
SetMethod · 0.85

Calls 5

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

Tested by

no test coverage detected