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

Function set_json_value

src/functions/json_functions.rs:1232–1276  ·  view source on GitHub ↗

Set value at path in JSON

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

Source from the content-addressed store, hash-verified

1230
1231/// Set value at path in JSON
1232fn set_json_value(json: &mut JsonValue, path: &[String], new_value: JsonValue) {
1233 if path.is_empty() {
1234 *json = new_value;
1235 return;
1236 }
1237
1238 // Navigate to the parent of the target
1239 let (parent_path, last_key) = path.split_at(path.len() - 1);
1240 let last_key = &last_key[0];
1241
1242 let mut current = json;
1243 for key in parent_path {
1244 match current {
1245 JsonValue::Object(map) => {
1246 current = map.entry(key.clone()).or_insert(JsonValue::Object(serde_json::Map::new()));
1247 }
1248 JsonValue::Array(arr) => {
1249 if let Ok(index) = key.parse::<usize>() {
1250 if index < arr.len() {
1251 current = &mut arr[index];
1252 } else {
1253 return;
1254 }
1255 } else {
1256 return;
1257 }
1258 }
1259 _ => return,
1260 }
1261 }
1262
1263 // Set the value at the last key
1264 match current {
1265 JsonValue::Object(map) => {
1266 map.insert(last_key.clone(), new_value);
1267 }
1268 JsonValue::Array(arr) => {
1269 if let Ok(index) = last_key.parse::<usize>()
1270 && index < arr.len() {
1271 arr[index] = new_value;
1272 }
1273 }
1274 _ => {},
1275 }
1276}
1277
1278/// Delete value at path in JSON
1279/// For objects: removes the key-value pair

Callers 1

register_json_functionsFunction · 0.85

Calls 4

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

Tested by

no test coverage detected