作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个 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?
最佳答案
因为您想使用 json-patch ,我假设您正在专门寻找 JSON Merge Patch (RFC 7396)实现,因为那是那个 crate 实现的。在这种情况下,合并一个对象应该取消设置那些在补丁中对应值为 null
的键,其他答案中的代码示例没有实现。
说明这一点的代码如下。我修改了补丁以删除 person.lastName
键,方法是将其设置为 null
作为演示。与其他答案之一不同,它也不需要 unwrap()
as_object_mut()
返回的 Option
。
use serde_json::{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 another title"
}
注意 person.lastName
已取消设置。
关于json - 如何用 Rust 合并两个 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47070876/
我是一名优秀的程序员,十分优秀!