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

标签 json rust serde json-patch serde-json

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

相关文章:

rust - Rust 的类型推断如何跨多个语句工作?

rust - 错误: `cannot find attribute in this scope` when using custom proc_macro with attributes written with darling in rust

java - 使用 Spring Boot 将 JSON 负载转换为 xml

java - 测试正确 JSON 序列化的最佳方法

python - Python 中的 JSON 导航 (PowerBI API)

java - Gson反序列化跳过一引号

rust - 如何指定工作区成员只能在特定平台上构建?

rust - Rust Serde反序列化混合数组

rust - 反序列化YAML的“Not general enough”错误

rust - Rust-使用serde/reqwest “Invalid type”反序列化