-
Notifications
You must be signed in to change notification settings - Fork 581
Can I merge two JSON objects using this library? #377
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
If you parse both pieces of JSON to the serde_json::Value enum then you can call as_object_mut or use |
Here is one possible implementation. I haven't tested it thoroughly but it works for your example. use serde_json::{json, Value};
fn merge(a: &mut Value, b: &Value) {
match (a, b) {
(Value::Object(a), Value::Object(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);
} |
@commandline Thank you for your suggestion. |
I don't think there are gotchas but depending on how the rest of your code is structured and specifically depending on whether you have ownership of |
Let's say I have the JSON below (JSON 1)
And another as follows (JSON 2)
How can I get the following output? (merging 2 into 1 where 2 Overrides 1)
I did checkout the crate json-patch which does this but it does not compile against stable rust. I want to know if its possible to do something similar with serde.
The text was updated successfully, but these errors were encountered: