json-patch, , JSON Merge Patch (RFC 7396), . , null
, .
The code that explains this is below. I changed the patch to remove the key person.lastName
, setting it to null
as a demo. Also, do not need unwrap()
on Option
, returned as_object_mut()
.
#[macro_use]
extern crate serde_json;
use serde_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);
}
Expected Result
{
"cities": [
"colombo"
],
"person": {
"firstName": "Jane"
},
"title": "This is a title"
}
Please note that person.lastName
not installed.
source
share