Recursive AI

Apply a YAML merge patch in Go

oneyaml-go is a free, open-source YAML library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.

Use ApplyMergePatch to override only the keys you name.

Terminal
go mod init demo
go get oneyaml.dev/go

Requires Go 1.24 or later.

GO
package main
import (
  "fmt"
  yaml "oneyaml.dev/go"
)
func main() {
  base := "replicas: 2 # scale\nold: true\n"
  doc, err := yaml.Parse([]byte(base))
  if err != nil { panic(err) }
  patch := "replicas: 3\nold: null\n"
  err = doc.ApplyMergePatch([]byte(patch))
  if err != nil { panic(err) }
  fmt.Print(doc)
}

go run . prints:

Text
replicas: 3 # scale

Unzip the example, then go run ..

The patch removes old, keeps the comment on replicas, and doesn’t write a file.

Check the error before using the result: for example, merging a mapping into a YAML alias (a *name reference to an anchored node) returns ErrAliasWrite rather than editing the shared mapping.

Variations

Use a JSON patch document with the same merge semantics. Replace the patch line with:

GO
patch := `{"replicas":3,"old":null}`

The program prints the same YAML. This is a JSON merge patch, not an array of JSON Patch operations.

The short answer

Parse the original YAML, then call ApplyMergePatch with the override. Write the result if the call succeeds. The patch describes the keys to change, so you don’t have to repeat unchanged settings or convert the original YAML to JSON first.

What is a JSON merge patch?

A JSON merge patch follows RFC 7396. For a mapping, a missing key in the patch leaves the original alone, a new key is added, and a null value removes that member. A nested mapping is merged into an existing mapping: an override of resources.limits.memory need not repeat resources.limits.cpu. If you supply an array for a key, it replaces the whole sequence. It doesn’t merge entries by index or by a name inside each entry.

You can write the patch as block YAML, as in the program, or as JSON. A patch starting with { or [ is read as JSON only, so {replicas: 3} is not an accepted shortcut for the block YAML. Use replicas: 3 on its own line, or quote the key as JSON requires. Merge-patch keys must be strings even when the patch is written as YAML.

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

Use Merge Patch for an override that reads like a small config file, such as raising a replica count and deleting an obsolete key. A mapping member set to null is a deletion, so it can’t also mean “keep the key but set its value to null.”

JSON Patch uses a list of operations with explicit paths instead. Use it when you need to append or change just one sequence item, set a value to null without deleting its key, or test the old value before making an edit. Those distinctions matter more than whether the patch itself is written using YAML or JSON syntax.

All oneyaml Go recipes