~/Parsing and Working with YAML in Go
Jul 14, 2021
YAML is a popular data format used in many configs. In Go, the widely used package for YAML is gopkg.in/yaml.v3.
To get started:
Install the package:
1
|
go get gopkg.in/yaml.v3
|
Sample Go struct and YAML data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
type Config struct {
Name string `yaml:"name"`
Debug bool `yaml:"debug"`
}
data := `
name: myapp
debug: true
`
var cfg Config
err := yaml.Unmarshal([]byte(data), &cfg)
if err != nil {
panic(err)
}
fmt.Println(cfg.Name) // Output: myapp
|
To marshal Go structs into YAML:
1
2
3
4
5
|
out, err := yaml.Marshal(&cfg)
if err != nil {
panic(err)
}
fmt.Println(string(out))
|
Always define struct tags for YAML keys to match field names.
For more, see the gopkg.in/yaml.v3 documentation.