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

Function setConfig

parser.go:1327–1460  ·  view source on GitHub ↗

SYS-REQ-115

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

Source from the content-addressed store, hash-verified

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