Delete value at path in JSON For objects: removes the key-value pair For arrays: removes the element at specified index Returns true if deletion was successful
(json: &mut JsonValue, path: &[String])
| 1280 | /// For arrays: removes the element at specified index |
| 1281 | /// Returns true if deletion was successful |
| 1282 | fn delete_json_value(json: &mut JsonValue, path: &[String]) -> bool { |
| 1283 | if path.is_empty() { |
| 1284 | return false; // Cannot delete root |
| 1285 | } |
| 1286 | |
| 1287 | // Navigate to the parent container and delete at the specified location |
| 1288 | let (parent_path, last_key) = path.split_at(path.len() - 1); |
| 1289 | let last_key = &last_key[0]; |
| 1290 | |
| 1291 | let mut current = json; |
| 1292 | for key in parent_path { |
| 1293 | match current { |
| 1294 | JsonValue::Object(map) => { |
| 1295 | // Check if the key exists before navigating |
| 1296 | if let Some(value) = map.get_mut(key) { |
| 1297 | current = value; |
| 1298 | } else { |
| 1299 | return false; // Key doesn't exist, cannot delete |
| 1300 | } |
| 1301 | } |
| 1302 | JsonValue::Array(arr) => { |
| 1303 | if let Ok(index) = key.parse::<usize>() { |
| 1304 | if index < arr.len() { |
| 1305 | current = &mut arr[index]; |
| 1306 | } else { |
| 1307 | return false; // Index out of bounds |
| 1308 | } |
| 1309 | } else { |
| 1310 | return false; // Invalid array index |
| 1311 | } |
| 1312 | } |
| 1313 | _ => return false, // Cannot navigate further |
| 1314 | } |
| 1315 | } |
| 1316 | |
| 1317 | // Delete the value at the last key |
| 1318 | match current { |
| 1319 | JsonValue::Object(map) => { |
| 1320 | // For objects, remove the key-value pair |
| 1321 | map.remove(last_key).is_some() |
| 1322 | } |
| 1323 | JsonValue::Array(arr) => { |
| 1324 | // For arrays, remove the element at the specified index |
| 1325 | if let Ok(index) = last_key.parse::<usize>() { |
| 1326 | if index < arr.len() { |
| 1327 | arr.remove(index); |
| 1328 | true |
| 1329 | } else { |
| 1330 | false // Index out of bounds |
| 1331 | } |
| 1332 | } else { |
| 1333 | false // Invalid array index |
| 1334 | } |
| 1335 | } |
| 1336 | _ => false, // Cannot delete from non-container types |
| 1337 | } |
| 1338 | } |
| 1339 |
no test coverage detected