go

How do I change the indent of a YAML sequence in goccy/go-yaml?


I have a YAML file which starts out like this:

additional_hostnames: []

I use goccy/go-yaml to parse it and add a new value like this:

    newHostnameNode := ast.String(token.New(hostname, hostname, &token.Position{}))
    additionalHostnames.IsFlowStyle = false
    additionalHostnames.Values = append(additionalHostnames.Values, newHostnameNode)

writing out I get:

additional_hostnames:
                      - foobar

which is really really close to what I wanted which is:

additional_hostnames:
  - foobar

any way to change the indent to be so?


Solution

  • Use the MarshalWithOptions function with Indent and IndentSequence options, e.g.:

    package main
    
    import (
        "fmt"
        "github.com/goccy/go-yaml"
    )
    
    func main() {
        data := struct {
            Items []string `yaml:"items"`
        }{
            Items: []string{"apple", "banana", "cherry"},
        }
    
        // Set indentation to 2 spaces.
        yamlData, err := yaml.MarshalWithOptions(data,
            yaml.Indent(2), yaml.IndentSequence(true))
        if err != nil {
            fmt.Println("Error marshaling data:", err)
            return
        }
        fmt.Println(string(yamlData))
    }
    

    The code above prints:

    items:
      - apple
      - banana
      - cherry
    

    For some reason, goccy/go-yaml has a special extra option, IndentSequence, to control the indentation of arrays and slices. But it automatically indents nested map items using the Indent option only.