Created
February 22, 2019 15:34
-
-
Save unixunion/1967780964c40af899473982e02cc099 to your computer and use it in GitHub Desktop.
Rust merging json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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