既然你想使用json 补丁 https://github.com/idubrov/json-patch,我假设您正在专门寻找JSON 合并补丁 (RFC 7396) https://www.rfc-editor.org/rfc/rfc7396实施,因为这就是那个箱子所实施的。在这种情况下,合并对象应该取消设置那些在补丁中对应值为null
,其他答案中的代码示例未实现。
解释这一点的代码如下。我修改了补丁删除了person.lastName
键,将其设置为null
作为演示。也不需要unwrap()
the Option
由返回as_object_mut()
,与其他答案之一不同。
use serde_json::{json, Value};
fn merge(a: &mut Value, b: Value) {
if let Value::Object(a) = a {
if let Value::Object(b) = b {
for (k, v) in b {
if v.is_null() {
a.remove(&k);
}
else {
merge(a.entry(k).or_insert(Value::Null), v);
}
}
return;
}
}
*a = b;
}
fn main() {
let mut a = json!({
"title": "This is a title",
"person" : {
"firstName" : "John",
"lastName" : "Doe"
},
"cities":[ "london", "paris" ]
});
let b = json!({
"title": "This is another title",
"person" : {
"firstName" : "Jane",
"lastName": null
},
"cities":[ "colombo" ]
});
merge(&mut a, b);
println!("{:#}", a);
}
预期输出是
{
"cities": [
"colombo"
],
"person": {
"firstName": "Jane"
},
"title": "This is another title"
}
Notice person.lastName
已取消设置。