YAML

suggest change

YAML is a popular format for serializing data in a human-friendly format. Think JSON, but easier to read.

Thanks to its expressiveness and readability, YAML is a popular format for configuration files.

It’s also used in more complex scenarios like driving Ansible server automation.

There is no YAML package in the standard library. Community libraries include gopkg.in/yaml.v2, used below, and the newer gopkg.in/yaml.v3. In v2, the default key is the lowercased field name.

Reading YAML file into a Go struct

dependencies:
  - name: apache
    version: 1.2.3
    repository: http://example.com/charts
  - name: mysql
    version: 3.2.1
    repository: http://another.example.com/charts
// Dependency describes a dependency
type Dependency struct {
	Name          string
	Version       string
	RepositoryURL string `yaml:"repository"`
}

type YAMLFile struct {
	Dependencies []Dependency `yaml:"dependencies"`
}

	f, err := os.Open("data.yml")
	if err != nil {
		log.Fatalf("os.Open() failed with '%s'\n", err)
	}
	defer f.Close()

	dec := yaml.NewDecoder(f)

	var yamlFile YAMLFile
	err = dec.Decode(&yamlFile)
	if err != nil {
		log.Fatalf("dec.Decode() failed with '%s'\n", err)
	}

	fmt.Printf("Decoded YAML dependencies: %#v\n", yamlFile.Dependencies)

YAML decoding is very similar to JSON decoding.

If you know the structure of the YAML file, define structs that mirror it and pass a pointer to the top-level struct to the yaml.Decoder.Decode method (or to yaml.Unmarshal when decoding a []byte).

The decoder matches a YAML key to the lowercased struct field name, so name is decoded into Name. Pass a pointer so the decoder can store into it.

It’s best to create explicit mappings using yaml struct tags. I only omitted them from the example to illustrate the behavior when they are not specified.

Writing Go struct to YAML file

type Person struct {
	fullName string
	Name     string
	Age      int    `yaml:"age"`
	City     string `yaml:"city"`
}

	p := Person{
		Name: "John",
		Age:  37,
		City: "SF",
	}
	d, err := yaml.Marshal(&p)
	if err != nil {
		log.Fatalf("yaml.Marshal failed with '%s'\n", err)
	}
	fmt.Printf("Person in YAML:\n%s\n", string(d))

yaml.Marshal takes interface{}. You can pass any Go value; it is wrapped in an interface{} with its dynamic type.

The marshaller uses reflection to inspect the value and encode it as YAML.

When serializing structs, only exported fields (names that start with a capital letter) are serialized and deserialized.

In this example, fullName is not serialized.

Structs are serialized as YAML dictionaries. With yaml.v2, the default key is the lowercased field name, so Name is serialized as name.

Custom names go in struct tags. yaml:"age" tells the encoder and decoder to use age for Age.

Passing the value or a pointer produces the same YAML. Passing a pointer avoids copying the struct.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents