Recursive AI

Apply a merge patch to YAML in C#

OneYaml is a free, open-source YAML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Apply a JSON Merge Patch (RFC 7396) to a YAML document, not the YAML << merge key.

Terminal
dotnet add package OneYaml

Targets .NET 8 and .NET 10; the download uses .NET 10.

C#
using OneYaml;
using var doc =
    YamlDocument.Parse("old: true\n");
doc.ApplyMergePatch(
    """{"old": null, "enabled": true}""");
Console.Write(doc);
Text
enabled: true

The snippet removes old and adds enabled in memory. If a patch tries to write through a YAML alias, OneYaml refuses the patch and leaves the document unchanged.

Unzip the example, then dotnet run.

Variations

Merge a nested mapping. Replace the code after using OneYaml; with this example. It replaces one label, adds a second, and leaves the rest of the document alone.

C#
using var doc = YamlDocument.Parse("name: web\nlabels: {tier: frontend}\n");
doc.ApplyMergePatch("""
    {"labels": {"tier": "backend", "team": "core"}}
    """);
Console.Write(doc);
Text
name: web
labels: {tier: backend, team: core}

Apply JSON Patch operations to YAML · Edit YAML without losing comments · Read YAML anchors and merge keys


The short answer

Parse the YAML with YamlDocument.Parse, then pass a JSON object to ApplyMergePatch. A JSON object merges into a YAML mapping key by key; a null member deletes the corresponding key. Print the document to see the result, or save it back to your settings file with File.WriteAllText(path, doc.ToString()), where path is the settings file path.

How do you merge YAML mappings in C#?

Put only the changes in the patch. In the nested example, the patch contains labels but not name, so name stays web. Inside labels, tier changes to backend and team is new. If the patch instead used "labels": null, the entire mapping and all its keys would be removed. If you need to write a literal YAML null instead of removing a key, use a document edit or a JSON Patch operation that sets the value.

Does a YAML merge patch use the same rules as JSON Merge Patch?

Yes. OneYaml takes a JSON Merge Patch (RFC 7396) and applies it to your YAML. The patch input is JSON text, UTF-8 JSON bytes or a JsonNode, not a second YAML document. A JSON array replaces the entire YAML sequence at that key; it doesn’t append items or merge them by index. For example, given ports: [80, 443], a patch containing "ports": [8080] leaves only 8080.

Merge Patch uses the shape of the desired change, whereas JSON Patch uses a list of named operations and paths. Merge Patch fits an update like “change these labels and remove this setting.” Use JSON Patch if you need to target a particular sequence item. Neither is the YAML << merge key, which is written inside the YAML itself to reuse values from another mapping.

All oneyaml C# recipes