---
title: "Decode a YAML string or list in Go"
url: https://recursiveai.org/oneyaml/go/cookbook/decode-flexible-yaml-list/
description: "Accept a YAML sequence or a comma-separated string in the same Go field, then work with both as []string."
version: "1.0.0"
---

# 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.

[pkg.go.dev](https://pkg.go.dev/oneyaml.dev/go) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-go) · [Docs](https://recursiveai.org/oneyaml/go/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/go/cookbook/decode-flexible-yaml-list/decode-flexible-yaml-list.zip)

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

```shell
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](https://recursiveai.org/oneyaml/go/cookbook/decode-flexible-yaml-list/decode-flexible-yaml-list.zip), 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])
}
```

## Related recipes

- [Parse YAML into a Go struct](https://recursiveai.org/oneyaml/go/cookbook/parse-yaml-into-structs/)
- [Read YAML in Go without a struct](https://recursiveai.org/oneyaml/go/cookbook/read-yaml-without-a-struct/)

## 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`](https://github.com/recursive-ai-oss/oneyaml-go/blob/7a4c8e39f041b945ee5f121c055f03bc2d7d01d9/example_func_hook_test.go#L11-L40) 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](https://recursiveai.org/oneyaml/go/docs/migrate-yaml-v3/#hooks), 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.
