Core functions for simple YAML encoding and decoding. Use these for straightforward marshaling and unmarshaling of YAML documents.
Serializes a Go value into a YAML document.
func Marshal(in interface{}) (out []byte, err error)in (interface{}) - The value to marshal. Accepts maps, pointers to structs, strings, ints, and other Go types.out ([]byte) - The serialized YAML document as a byte sliceerr (error) - Error if marshaling fails, nil otherwiseyaml struct tagsomitempty tag to exclude)package main
import (
"fmt"
"log"
"gopkg.in/yaml.v3"
)
type Config struct {
Name string
Port int `yaml:"port"`
Enabled bool `yaml:"enabled,omitempty"`
}
func main() {
config := Config{
Name: "MyService",
Port: 8080,
Enabled: true,
}
data, err := yaml.Marshal(&config)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", data)
// Output:
// name: MyService
// port: 8080
// enabled: true
}`yaml:"[<key>][,<flag1>[,<flag2>]]"`Supported flags:
omitempty - Omit field if zero valueflow - Use flow style for structs, sequences, and mapsinline - Inline struct or map fields into parent struct"-" to ignore the fieldtype Person struct {
Name string `yaml:"name"`
Age int `yaml:"age,omitempty"`
Hobbies []string `yaml:"hobbies,flow"`
Metadata map[string]string `yaml:",inline"`
Internal string `yaml:"-"`
}
p := Person{
Name: "Alice",
Age: 0, // Will be omitted due to omitempty
Hobbies: []string{"reading", "coding"},
Metadata: map[string]string{"role": "developer"},
Internal: "not exported",
}
data, _ := yaml.Marshal(&p)
fmt.Printf("%s", data)
// Output:
// name: Alice
// hobbies: [reading, coding]
// role: developerDecodes the first YAML document found within a byte slice and assigns values into a Go variable.
func Unmarshal(in []byte, out interface{}) (err error)in ([]byte) - The YAML document as a byte sliceout (interface{}) - Pointer to the variable where decoded values will be stored. Must not be nil.err (error) - Returns *yaml.TypeError if one or more fields cannot be decoded due to type mismatches. Unmarshaling continues partially. Returns nil on success.out valuesout parameter must not be nilyaml struct tags*yaml.TypeError containing all errorspackage main
import (
"fmt"
"log"
"gopkg.in/yaml.v3"
)
type Config struct {
Name string
Port int `yaml:"port"`
Database struct {
Host string
Port int
}
}
func main() {
data := []byte(`
name: MyService
port: 8080
database:
host: localhost
port: 5432
`)
var config Config
err := yaml.Unmarshal(data, &config)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Name: %s\n", config.Name)
fmt.Printf("Port: %d\n", config.Port)
fmt.Printf("DB: %s:%d\n", config.Database.Host, config.Database.Port)
}data := []byte(`
name: Alice
age: 30
active: true
`)
var result map[string]interface{}
err := yaml.Unmarshal(data, &result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", result)
// Output: map[active:true age:30 name:Alice]type Config struct {
Port int
}
data := []byte(`port: "not a number"`)
var config Config
err := yaml.Unmarshal(data, &config)
if err != nil {
if typeErr, ok := err.(*yaml.TypeError); ok {
for _, errMsg := range typeErr.Errors {
fmt.Println("Unmarshal error:", errMsg)
}
}
}Both Marshal and Unmarshal respect struct field tags for customization:
type T struct {
Field int `yaml:"custom_name"`
}
// YAML key will be "custom_name" instead of "field"type T struct {
Field int `yaml:"field,omitempty"`
}
// Field is omitted from output if it has zero valueThe omitempty flag respects the IsZeroer interface. If a struct implements IsZero() bool, that method determines whether the field is omitted.
type T struct {
Items []int `yaml:"items,flow"`
}
// Output: items: [1, 2, 3]
// Instead of:
// items:
// - 1
// - 2
// - 3type Metadata struct {
CreatedAt string
UpdatedAt string
}
type Document struct {
Title string
Metadata Metadata `yaml:",inline"`
}
// The Metadata fields become top-level keys:
// title: Example
// createdat: 2023-01-01
// updatedat: 2023-01-02type T struct {
Public string
Internal string `yaml:"-"`
}
// Internal field is completely ignored during marshaling/unmarshalingMap keys must be comparable types. Common map types:
map[string]interface{} // Most flexible
map[string]string // String values only
map[interface{}]interface{} // Any key/value typenull in YAMLomitempty is used