Recursive AI

Add a YAML key in Go without losing comments

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

Call doc.Set("/owner", "ops") to add owner at the end of the mapping.

Terminal
go get oneyaml.dev/go

Requires Go 1.24+. Run in a Go module.

GO
package main
 
import (
	"fmt"
	"log"
 
	"oneyaml.dev/go"
)
 
func main() {
	input := "# API settings\n" +
		"name: 'api' # public name\n\nport: 80\n"
	doc, err := oneyaml.Parse([]byte(input))
	if err != nil {
		log.Fatal(err)
	}
	if err := doc.Set("/owner", "ops"); err != nil {
		log.Fatal(err)
	}
	fmt.Print(doc)
}

Unzip the example, then go run ..

The output adds owner after port and keeps the comment, quote marks, and blank line.

Text
# API settings
name: 'api' # public name
 
port: 80
owner: 'ops'

If the parent doesn’t exist, Set returns an error; it won’t build the missing path.

Variations

Add the key inside a nested mapping. Replace the input assignment and the Set block with the following. Keep the Parse call and its error check between them.

GO
input := "service:\n  port: 80 # public port\n"
GO
if err := doc.Set("/service/owner", "ops"); err != nil {
	log.Fatal(err)
}
Text
service:
  port: 80 # public port
  owner: ops

Read a YAML file and save a copy with the new key. Save this as config.yaml next to main.go, add "os" to the imports, and replace the body of main with the code below.

YAML
# API settings
port: 80 # public port
GO
input, err := os.ReadFile("config.yaml")
if err != nil {
	log.Fatal(err)
}
doc, err := oneyaml.Parse(input)
if err != nil {
	log.Fatal(err)
}
if err := doc.Set("/owner", "ops"); err != nil {
	log.Fatal(err)
}
if err := os.WriteFile("updated.yaml", doc.Bytes(), 0644); err != nil {
	log.Fatal(err)
}
fmt.Print(doc)

This prints the contents of updated.yaml and leaves config.yaml unchanged.

Text
# API settings
port: 80 # public port
owner: ops

The short answer

Parse the source with Parse, then call doc.Set("/owner", "ops"). A missing final key in an existing mapping is appended; an existing key is updated instead. Use doc.Bytes() for the edited YAML; fmt.Print(doc) displays the same text. This changes the document in memory, not the source file on disk. To update a file, write the returned bytes only after the edit succeeds.

How do you add data to an existing YAML file without losing comments?

Edit the source document instead of decoding it to a Go struct or map and marshaling that data again. A Go map stores values, not the comment next to name, the blank line after it, or the single quotes in the original text. In the snippet at the top, the new entry is inserted after port, and the original entries stay put. The new value borrows the quoting style of a nearby string value, which is why the output shows 'ops' rather than ops.

Style follows the mapping you’re actually editing. In a block mapping, the entry gets the indentation of its neighbors. A flow mapping, written with braces, gets another entry inside the braces rather than a new block on the next line. That distinction matters when reviewing a diff: adding a key doesn’t require reserializing the entire document. See Adding and removing for how Set chooses insertion style.

How do you add a key under another YAML key in Go?

Pass the full path to the new entry. /service/owner means “add owner to the mapping under service,” not “replace service with owner.” The parent must already exist and be a mapping for this use of Set. Keep unrelated settings in the parent by targeting the new entry alone, as in the variation above.

The path is a JSON Pointer, so a literal slash in a key is not the same as a slash separating two keys. If a name comes from a caller, build the path with oneyaml.Pointer("service", key). It handles the escaping for / and ~. Finally, decide what should happen if the key is already present: Set is an add-or-update operation. If your tool must never overwrite an existing key, check the parent with Node.Find first. Proceed only on ErrNotFound; an ambiguous lookup is not a missing key.

All oneyaml Go recipes