Recursive AI

Decode a YAML string or list in Go

oneyaml-go is a free, open-source YAML library for Go from Recursive AI. MIT or Apache-2.0, no dependencies.

Use UnmarshalYAML to read [api, web] or "jobs,cache" into the same Go slice type.

Terminal
go get oneyaml.dev/go@v1.0.0

Requires Go 1.24 or later. Run go get in a Go module.

GO
package main
 
import (
    "fmt"
    "strings"
    yaml "oneyaml.dev/go"
)
 
type Labels []string
 
func (v *Labels) UnmarshalYAML(
    decode func(any) error,
) error {
    var list []string
    if err := decode(&list); err == nil {
        *v = list
        return nil
    }
    var text string
    if err := decode(&text); err != nil {
        return err
    }
    *v = strings.Split(text, ",")
    return nil
}
 
func main() {
    const input = `front: [api, web]
back: "jobs,cache"
`
    var cfg map[string]Labels
    if err := yaml.Unmarshal(
        []byte(input), &cfg,
    ); err != nil {
        panic(err)
    }
    fmt.Printf("front: %q\n", cfg["front"])
    fmt.Printf("back: %q\n", cfg["back"])
}

Unzip the example, then go run ..

Text
front: ["api" "web"]
back: ["jobs" "cache"]

The full program

The download uses the same input with named struct fields instead of a map. Both fields use the same Labels type.

GO
package main
 
import (
	"fmt"
	"log"
	"strings"
 
	yaml "oneyaml.dev/go"
)
 
// Labels accepts a YAML sequence or a comma-separated string.
type Labels []string
 
func (labels *Labels) UnmarshalYAML(decode func(any) error) error {
	var list []string
	if err := decode(&list); err == nil {
		*labels = list
		return nil
	}
	var text string
	if err := decode(&text); err != nil {
		return fmt.Errorf("expected a sequence or comma-separated string: %w", err)
	}
	*labels = strings.Split(text, ",")
	return nil
}
 
func main() {
	const input = `front: [api, web]
back: "jobs,cache"
`
	var config struct {
		Front Labels `yaml:"front"`
		Back  Labels `yaml:"back"`
	}
	if err := yaml.Unmarshal([]byte(input), &config); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("front: %q\nback: %q\n", config.Front, config.Back)
}

go run . prints:

Text
front: ["api" "web"]
back: ["jobs" "cache"]

If neither decode works, the hook returns an error and the program prints no lists.

Variations

Trim spaces in the comma-separated form. Add this after strings.Split and before the final return nil in the full program’s hook. With back: "jobs, cache", the second entry is "cache", not " cache".

GO
for i := range *labels {
    (*labels)[i] = strings.TrimSpace((*labels)[i])
}

The short answer

Define a slice type such as Labels and implement UnmarshalYAML(decode func(any) error) on *Labels. Try decoding into []string first. If that fails, try a string and split it on commas. Use Labels as the type of any field that accepts both forms. The rest of the program works with a slice, regardless of how the input was written.

How do you write a custom YAML unmarshaler in Go?

In oneyaml-go, the callback form of UnmarshalYAML gives the method a function that decodes the current YAML value into a destination you choose. That destination is a pointer, just like the second argument of Unmarshal. Calling the function twice tries two Go types against the same YAML value; it doesn’t advance to another field. The pointer receiver lets the method replace the caller’s slice once a decode succeeds. This signature matches the older callback hook in the migration guide, not the hook that takes a YAML node.

Put the method on the field type rather than the entire configuration type. Then the parser still fills in the surrounding struct normally, and the same hook handles both front and back. A field that should only accept a YAML sequence can stay []string; it won’t pick up the fallback. Inside the hook, decode the sequence into a plain []string, not into Labels again, so the callback doesn’t call the same hook recursively.

How do you unmarshal YAML into either a string or a list?

Decide what the scalar means before you split it. In this recipe a comma inside the scalar separates labels. A comma inside a sequence item is ordinary string content: ["jobs,cache", api] gives two entries, the first of which is "jobs,cache". A scalar "jobs,cache" also gives two entries, but they’re "jobs" and "cache". The sequence is the better format when the labels themselves can contain commas.

strings.Split does not trim spaces or discard empty items. For example, "jobs,,cache" has an empty middle entry. Choose whether to keep or reject it based on what an empty label means in your app. If you control the configuration format, you can document a sequence as the preferred form and accept the scalar only as a convenience. Neither form needs a different field name or a separate read path in the application.

All oneyaml Go recipes