Merge two JSON objects in Rust
December 9, 2019•130 words
This is the most shared code snippet on StackOverflow for merging two JSON objects in Rust:
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;
}
The problem with this code snippet is, it will override any Array values, for example:
ORIGINAL:
{
"languages": [ "c++", "rust", "java" ]
}
INCOMING:
{
"languages": [ "javascript" ]
}
The output would be:
{
"languages": [ "javascript" ]
}
Most JSON merger has an option to append instead of override, some even has the ability to do more complex works 1.