UNIT-L
MAIN OUTPUT SECTOR
UNIT-R

Parsing YAML in Go

gopkg.in/yaml.v2

Assuming config.yaml is in the same directory as your entry file.

1
2
3
4
5
6
TodoLists:
- Test 1
- Test 2
- Test 3

CloudKey: adasdx7817238123213

Here’s how to parse it into a struct:

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
package main

import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)

// Define the structure to match the YAML
type TodoLists struct {
// Use tags to map YAML keys to struct fields
Lists []string `yaml:"TodoLists"`
CloudKey string `yaml:"CloudKey"`
}

func main(){
// Initialize the struct
todolists := TodoLists{}
filePath := "./config.yaml"

buffer, err := ioutil.ReadFile(filePath)

if err != nil {
panic(err)
}

// Unmarshal the YAML data into the struct
err = yaml.Unmarshal(buffer, &todolists)
if err != nil {
panic(err)
}

// Iterate and print the list
for _, value := range todolists.Lists {
fmt.Println(value)
}
}

// Output:
// Test 1
// Test 2
// Test 3