Use PatchAdd at /jobs/1 to insert before the second item in the jobs list. The existing item moves down instead of being replaced.
go get oneyaml.dev/go@v1.0.0Go 1.24+.
package main import ( "fmt" "os" yaml "oneyaml.dev/go" ) func main() { input := `jobs: - lint # first - deploy # last ` doc, err := yaml.Parse([]byte(input)) if err != nil { panic(err) } op := yaml.PatchAdd("/jobs/1", "test") if err := doc.Apply(op); err != nil { panic(err) } if err := os.WriteFile("updated.yaml", doc.Bytes(), 0644); err != nil { panic(err) } fmt.Print(doc) }
Paste the code above into main.go, run go mod init example and go get oneyaml.dev/go@v1.0.0, then go run .; or unzip the example and go run ..
go run . writes updated.yaml and prints the same YAML:
jobs: - lint # first - test - deploy # last
An index greater than the sequence length is an error and leaves the document unchanged.
Variations
Insert before the first item. Replace the op line with:
op := yaml.PatchAdd("/jobs/0", "test")It prints:
jobs: - test - lint # first - deploy # last
Related recipes
The short answer
Parse the existing bytes as a Document and apply PatchAdd at the index where the new item should go. The indices are zero-based: /jobs/1 inserts before the old second item. Read the updated YAML from the document. To save the edit, write those bytes where you want them; applying the patch doesn’t write a file.
How do I write a sequence in YAML without changing its indentation?
A block sequence uses a dash and a space before each item. In the example, both existing dashes sit two spaces in from jobs:. The patch uses the document’s local style for the inserted item rather than taking an indentation setting for the whole file. The trailing comments still belong to lint and deploy; test gets its own line between them.
Not every sequence uses dashes. A flow sequence such as [lint, deploy] uses brackets and commas. The path still selects an index, not a line or column. A document edit works on the existing YAML instead of decoding the file into ordinary Go values and marshaling a new copy.
How do I insert into a YAML list instead of replacing an item?
Choose PatchAdd to insert and Document.Set to assign. If the list has two items, index 1 refers to a position already occupied. The add operation shifts that item and leaves three items; assigning at index 1 writes over the occupant and leaves two. Index 0 inserts at the front. If your intent is always to append, use the - token instead of computing a numeric index.
A pointer uses the document’s current positions. For a patch with multiple inserts, count from the sequence as it stands at each operation, not just when you started. If a later operation fails, the entire patch is rejected. This lets you keep a set of related edits together without saving a partially updated file.