Use SetLineComment to change the note after a YAML value without changing the value itself.
go get oneyaml.dev/goRequires Go 1.24+. Run in a Go module.
package main import ( "fmt" "log" "oneyaml.dev/go" ) func main() { input := "port: 8080 # temporary\n" doc, err := oneyaml.Parse( []byte(input), ) if err != nil { log.Fatal(err) } err = doc.SetLineComment( "/port", "public port", ) if err != nil { log.Fatal(err) } fmt.Print(doc) }
port: 8080 # public portThe output still has port: 8080. If the location can’t hold an inline comment, the edit returns ErrUnsupportedEdit.
Unzip the example, then go run ..
Variations
Save the edited YAML. Import os, set path to the file to write (for example, "config.yaml"), and replace fmt.Print(doc) with this line. Remove the unused fmt import and check err after the write.
err = os.WriteFile(path, doc.Bytes(), 0o644)Remove the comment. In the snippet at the top, replace the SetLineComment call with this one and keep the error check. The output becomes port: 8080.
err = doc.SetLineComment("/port", "")Target a nested key. Replace the input and the SetLineComment call below, leaving the parse, error checks, and print in place. /service/port selects port inside service.
// Replace the input before Parse. input := "service:\n" + " port: 8080 # temporary\n" // Replace the edit after Parse. err = doc.SetLineComment( "/service/port", "public", )
service: port: 8080 # public
Related recipes
The short answer
Parse the YAML as a document, call SetLineComment with the path and the new text, and use doc.Bytes() to get the edited YAML if you need to save it. /port is the path to the top-level key in the example. Pass the comment text without #; the editor adds it. Pass an empty string to remove the existing inline comment without removing the key or changing its value.
How do you comment on the same line in YAML?
Put a space and # after the value, as in port: 8080 # public port. A # inside a quoted string is part of that string, not a comment. The YAML spec treats comments as presentation, not as data. That’s why changing the note doesn’t change the port a YAML reader gets, and why editing the decoded number and serializing it again isn’t the way to update the note.
Where the editor puts the comment depends on the value. For ports: [80, 443], it goes after the closing bracket. For message: |, it goes on the header line after the pipe, not on one of the indented text lines. If a comma or another token follows the target on the same line, a comment there could hide the rest of the YAML, so the editor refuses that placement. A line break in the comment text returns ErrInvalidComment; use a comment above the key for a note that needs multiple lines.