use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Map, Value};
pub fn apply<T>(current: T, patch_json: &str) -> Result<T, serde_json::Error>
where
T: Serialize + DeserializeOwned,
{
let mut current_val = serde_json::to_value(current)?;
let patch_val: Value = serde_json::from_str(patch_json)?;
merge_patch(&mut current_val, &patch_val);
serde_json::from_value(current_val)
}
fn merge_patch(target: &mut Value, patch: &Value) {
if let Value::Object(patch_map) = patch {
if !target.is_object() {
*target = Value::Object(Map::new());
}
let target_map = target.as_object_mut().unwrap();
for (key, patch_value) in patch_map {
if patch_value.is_null() {
target_map.remove(key);
} else {
let target_entry = target_map.entry(key.clone()).or_insert(Value::Null);
merge_patch(target_entry, patch_value);
}
}
} else {
*target = patch.clone();
}
}