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.
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) }
# 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.
Setwrites 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.
SetHeadCommentwrites the comment above an entry,SetLineCommentthe 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.
Setrefuses 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
yesis 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 withYAML11Strings()so such strings are quoted.
Every rule is in Editing. To change many values from a JSON document, use a patch: merge or patch YAML.
The same edit in Go, Rust and C#: Edit YAML without losing comments.