How can I merge two JSON objects with Rust?
Placing the answer suggested by Shepmaster below
#[macro_use]
extern crate serde_json;
use serde_json::Value;
fn merge(a: &mut Value, b: Value) {
match (a, b) {
(a @ &mut Value::Object(_), Value::Object(b)) => {
let a = a.as_object_mut().unwrap();
for (k, v) in b {
merge(a.entry(k).or_insert(Value::Null), v);
}
}
(a, b) => *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"
},
"cities":[ "colombo" ]
});
merge(&mut a, b);
println!("{:#}", a);
}
Since you wanted to use json-patch, I assume you were looking specifically for a JSON Merge Patch (RFC 7396) implementation which is what that crate implements. In that case, merging an object should unset those keys whose corresponding value in the patch is null
, which the code samples in the other answers do not implement.
The code that accounts for that is below. I modified the patch to delete the person.lastName
key by setting it to null
as a demonstration. It also does not need to unwrap()
the Option
returned by 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);
}
The expected output is
{
"cities": [
"colombo"
],
"person": {
"firstName": "Jane"
},
"title": "This is a title"
}
Notice person.lastName
has been unset.