我有两个JSON文件:
JSON 1
{
"title": "This is a title",
"person" : {
"firstName" : "John",
"lastName" : "Doe"
},
"cities":[ "london", "paris" ]
}
JSON 2
{
"title": "This is another title",
"person" : {
"firstName" : "Jane"
},
"cities":[ "colombo" ]
}
我想将#2合并到#1,其中#2覆盖#1,产生以下输出:
{
"title": "This is another title",
"person" : {
"firstName" : "Jane",
"lastName" : "Doe"
},
"cities":[ "colombo" ]
}
我检查了执行此操作的crate json-patch,但它不能针对稳定的Rust进行编译。是否有可能做类似serde_json和稳定的Rust?
之类的事情答案 0 :(得分:5)
将Shepmaster建议的答案放在
下面#[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);
}
答案 1 :(得分:1)
这对我有用
#[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);
}
答案 2 :(得分:1)
由于您想使用json-patch,因此我假设您正在专门寻找crate实现的JSON Merge Patch (RFC 7396)实现。在这种情况下,合并对象应该取消设置其补丁中的对应值为null
的那些键,而其他答案中的代码示例将不实现这些键。
解释该问题的代码如下。我通过将补丁设置为person.lastName
来修改补丁程序以删除null
键。它还不需要unwrap()
Option
返回的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);
}
预期输出为
{
"cities": [
"colombo"
],
"person": {
"firstName": "Jane"
},
"title": "This is a title"
}
通知person.lastName
尚未设置。