gpt4 book ai didi

json - 如何用 Rust 合并两个 JSON 对象?

转载 作者:行者123 更新时间:2023-11-29 07:50:08 25 4
gpt4 key购买 nike

我有两个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com