[Awesome Go] Use yaml package to encode and decode YAML values

YAML support for the Go language

The yaml package enables Go programs to comfortably encode and decode YAML values. It was developed within Canonical as part of the juju project, and is based on a pure Go port of the well-known libyaml C library to parse and generate YAML data quickly and reliably.

Installation

Standard go get:

1
$ go get -u gopkg.in/yaml.v2

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
"fmt"
"log"

"gopkg.in/yaml.v2"
)

var data = `
a: Easy!
b:
c: 2
d: [3, 4]
`

// Note: struct fields must be public in order for unmarshal to
// correctly populate the data.
type T struct {
A string
B struct {
RenamedC int `yaml:"c"`
D []int `yaml:",flow"`
}
}

func main() {
t := T{}

err := yaml.Unmarshal([]byte(data), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t:\n%v\n\n", t)

d, err := yaml.Marshal(&t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t dump:\n%s\n\n", string(d))

m := make(map[interface{}]interface{})

err = yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)

d, err = yaml.Marshal(&m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m dump:\n%s\n\n", string(d))
}

This example will generate the following output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
--- t:
{Easy! {2 [3 4]}}

--- t dump:
a: Easy!
b:
c: 2
d: [3, 4]


--- m:
map[a:Easy! b:map[c:2 d:[3 4]]]

--- m dump:
a: Easy!
b:
c: 2
d:
- 3
- 4

FAQs

yaml:",flow"

References

[1] GitHub - go-yaml/yaml: YAML support for the Go language. - https://github.com/go-yaml/yaml

[2] yaml · pkg.go.dev - https://pkg.go.dev/gopkg.in/yaml.v2