---
title: "Edit YAML and keep its comments"
url: https://recursiveai.org/oneyaml/go/cookbook/edit-yaml-keep-comments/
description: "Change a value, remove a list item, add a key with a comment and rename a key in a YAML file from Go, with every other byte and comment kept."
version: "1.0.0"
---

# Edit YAML and keep its comments

Change a YAML file from Go the way a person would: one value, one list item, one new key, one renamed key. Every comment, blank line and quote elsewhere stays as it was.

```go
package main

import (
	"fmt"
	"log"

	oneyaml "oneyaml.dev/go"
)

func main() {
	doc, err := oneyaml.Parse([]byte(`# App settings, edited by hand and by tools.
server:
  host: 0.0.0.0
  port: 8080      # behind the load balancer

# Feature flags
features:
  - auth
  - legacy-export   # remove after the 2.0 release
  - metrics
`))
	if err != nil {
		log.Fatal(err)
	}
	must := func(err error) {
		if err != nil {
			log.Fatal(err)
		}
	}

	must(doc.Set("/server/port", 9090))                        // its trailing comment stays
	must(doc.Remove("/features/1"))                            // its comment goes with it
	must(doc.Set("/server/timeout", "30s"))                    // a new key, laid out like its siblings
	must(doc.SetLineComment("/server/timeout", "per request")) // a comment of its own
	must(doc.Rename("/server/host", "bind"))                   // a key renamed in place

	fmt.Print(doc)
}
```

```text
# App settings, edited by hand and by tools.
server:
  bind: 0.0.0.0
  port: 9090      # behind the load balancer
  timeout: 30s # per request

# Feature flags
features:
  - auth
  - metrics
```

## Good to know

- **Each value keeps its style.** `Set` writes in the old value’s style and falls back to the nearest style that can hold the new value, for that value only. Reading the document back always gives exactly the value you set.
- **Comments:** a comment after a value stays when the value changes, and a removed item takes its own comment with it. `SetHeadComment` writes the comment above an entry, `SetLineComment` the one after its value; an empty text removes it.
- **New members** go at the end of their mapping and copy the style of their siblings.
- **Refusals are errors, not damage.** `Set` refuses to write below an alias or to a key that occurs twice. On any error the document is unchanged and the error is an `*EditError`.
- A new plain `yes` is a string under YAML 1.2 but a boolean to a YAML 1.1 reader. If YAML 1.1 programs also read the file, parse it with `YAML11Strings()` so such strings are quoted.

Every rule is in [Editing](https://recursiveai.org/oneyaml/go/docs/editing/). To change many values from a JSON document, use a patch: [merge or patch YAML](https://recursiveai.org/oneyaml/go/cookbook/patch-yaml/).

The same edit in Go, Rust and C#: [Edit YAML without losing comments](https://recursiveai.org/oneyaml/articles/edit-yaml-keep-comments/).
