Skip to content

Instantly share code, notes, and snippets.

@unixunion
Created February 22, 2019 15:34
Show Gist options
  • Save unixunion/1967780964c40af899473982e02cc099 to your computer and use it in GitHub Desktop.
Save unixunion/1967780964c40af899473982e02cc099 to your computer and use it in GitHub Desktop.
Rust merging json
#[macro_use]
extern crate serde_json;
use serde_json::Value;
fn merge(a: &mut Value, b: &Value) {
match (a, b) {
(&mut Value::Object(ref mut a), &Value::Object(ref b)) => {
for (k, v) in b {
merge(a.entry(k.clone()).or_insert(Value::Null), v);
}
}
(a, b) => {
*a = b.clone();
}
}
}
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment