---
title: "Apply a JSON Merge Patch to YAML in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/apply-yaml-merge-patch/
description: "Apply an RFC 7396 merge patch to YAML in Rust: update nested settings, remove keys with null, and keep comments and formatting outside the changes."
version: "1.2.0"
---

# Apply a JSON Merge Patch to YAML in Rust

**oneyaml** is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

[crates.io](https://crates.io/crates/oneyaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-rust) · [Docs](https://recursiveai.org/oneyaml/rust/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/rust/cookbook/apply-yaml-merge-patch/apply-yaml-merge-patch.zip)

Call `apply_merge_patch` to override YAML settings in place. In the patch, `null` removes a key.

```shell
cargo add oneyaml
```

```rust
use oneyaml::{Document, MergePatch};

fn main() -> Result<
    (), Box<dyn std::error::Error>,
> {
    let mut doc = Document::parse(concat!(
        "service:\n",
        "  replicas: 2  # scale\n",
        "  debug: true\n",
        "  region: west\n",
    ))?;
    let patch = MergePatch::from_json(
        r#"{"service": {
          "replicas": 3, "debug": null
        }}"#,
    )?;
    doc.apply_merge_patch(&patch)?;
    print!("{doc}");
    Ok(())
}
```

Prints the updated YAML:

```text
service:
  replicas: 3  # scale
  region: west
```

The program doesn’t write a file. A failed patch returns `PatchError` and leaves the document unchanged. The example uses Rust 1.85 or later.

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/apply-yaml-merge-patch/apply-yaml-merge-patch.zip), then `cargo run`.

## Variations

`MergePatch::from_json` accepts both JSON and YAML patch text. Replace the call with this YAML patch to change only `replicas`:

```rust
let patch = MergePatch::from_json(
    "service: {replicas: 3}",
)?;
```

```text
service:
  replicas: 3  # scale
  debug: true
  region: west
```

To save the result back to a file, create `config.yaml` with the original YAML from the snippet above. Replace the body of `main` with this code. It writes to the same file only after the patch succeeds:

```rust
let path = "config.yaml";
let yaml = std::fs::read_to_string(path)?;
let mut doc = Document::parse(&yaml)?;
let patch = MergePatch::from_json(
    "service: {replicas: 3, debug: null}",
)?;
doc.apply_merge_patch(&patch)?;
std::fs::write(path, doc.to_string())?;
Ok(())
```

`config.yaml` now contains:

```yaml
service:
  replicas: 3  # scale
  region: west
```

## Related recipes

- [Apply a JSON Patch to YAML in Rust](https://recursiveai.org/oneyaml/rust/cookbook/patch-yaml/)
- [Edit YAML and keep its comments in Rust](https://recursiveai.org/oneyaml/rust/cookbook/edit-yaml-keep-comments/)

---

## The short answer

Parse the original YAML as a `Document`. Parse the overlay with `MergePatch::from_json`, then call `doc.apply_merge_patch(&patch)`. This applies [RFC 7396](https://www.rfc-editor.org/rfc/rfc7396) rules directly to the YAML document: it merges mappings by key and leaves the surrounding document text in place. You don’t need to convert the original file to JSON.

## What’s the difference between JSON Patch and JSON Merge Patch?

A JSON Merge Patch looks like a partial copy of the document, while a [JSON Patch (RFC 6902)](https://www.rfc-editor.org/rfc/rfc6902) lists operations with paths.

In the example, `service` identifies a mapping. Inside it, `replicas: 3` replaces one value, `debug: null` deletes a key, and omitting `region` leaves it alone. The `# scale` comment stays with the replaced scalar in this example. [Comments and layout outside the changed values stay as they are](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/document/patch/mod.rs#L739-L741).
Choose it if you need to check the old value with `test`, insert into a sequence, or set a mapping field to an explicit null rather than delete it. Merge Patch doesn’t check the old value and doesn’t distinguish between “set this field to null” and “remove this field.” A field already set to null stays that way if the patch leaves it out.

## Does JSON Merge Patch replace an entire array?

Yes. A YAML sequence is treated like a JSON array: its new list replaces the old list as a whole, even inside a merged mapping. If a config lists ports `[80, 443]`, a patch giving only `[8443]` leaves just `8443`; it doesn’t add a third port. Use an explicit JSON Patch `add` operation if you want to add one port without repeating the others.

The same replacement rule applies at the root. If the patch is a list or scalar instead of a mapping, it replaces the entire document. When reading an override supplied by someone else, check that its root is the kind of patch you intend to accept, rather than assuming it’s a mapping.
