MCPcopy Create free account
hub / github.com/erans/pgsqlite / insert_json_value

Function insert_json_value

src/functions/json_functions.rs:1344–1411  ·  view source on GitHub ↗

Insert value at path in JSON For objects: inserts a new key-value pair For arrays: inserts value at specified index (insert_after determines before/after) Returns true if insertion was successful

(json: &mut JsonValue, path: &[String], new_value: JsonValue, insert_after: bool)

Source from the content-addressed store, hash-verified

1342/// For arrays: inserts value at specified index (insert_after determines before/after)
1343/// Returns true if insertion was successful
1344fn insert_json_value(json: &mut JsonValue, path: &[String], new_value: JsonValue, insert_after: bool) -> bool {
1345 if path.is_empty() {
1346 return false; // Cannot insert at root
1347 }
1348
1349 // Navigate to the parent container and insert at the specified location
1350 let (parent_path, last_key) = path.split_at(path.len() - 1);
1351 let last_key = &last_key[0];
1352
1353 let mut current = json;
1354 for key in parent_path {
1355 match current {
1356 JsonValue::Object(map) => {
1357 // Check if the key exists before navigating
1358 if let Some(value) = map.get_mut(key) {
1359 current = value;
1360 } else {
1361 return false; // Key doesn't exist, cannot insert
1362 }
1363 }
1364 JsonValue::Array(arr) => {
1365 if let Ok(index) = key.parse::<usize>() {
1366 if index < arr.len() {
1367 current = &mut arr[index];
1368 } else {
1369 return false; // Index out of bounds
1370 }
1371 } else {
1372 return false; // Invalid array index
1373 }
1374 }
1375 _ => return false, // Cannot navigate further
1376 }
1377 }
1378
1379 // Insert the value at the last key
1380 match current {
1381 JsonValue::Object(map) => {
1382 // For objects, insert new key-value pair (only if key doesn't exist)
1383 if !map.contains_key(last_key) {
1384 map.insert(last_key.clone(), new_value);
1385 true
1386 } else {
1387 false // Key already exists
1388 }
1389 }
1390 JsonValue::Array(arr) => {
1391 // For arrays, insert at the specified index
1392 if let Ok(index) = last_key.parse::<usize>() {
1393 let insert_index = if insert_after {
1394 index + 1
1395 } else {
1396 index
1397 };
1398
1399 if insert_index <= arr.len() {
1400 arr.insert(insert_index, new_value);
1401 true

Callers 1

register_json_functionsFunction · 0.85

Calls 4

is_emptyMethod · 0.45
lenMethod · 0.45
insertMethod · 0.45
cloneMethod · 0.45

Tested by

no test coverage detected