DEV Community

Cover image for Generate YAML files in Golang.
SagarTrimukhe
SagarTrimukhe

Posted on

Generate YAML files in Golang.

This is post is about converting go struct/map into a yaml using this amazing go package go-yaml

We will be using yaml.Marshal method to convert a struct into yaml.

Each of the examples will have complete code, so that users can copy paste and quickly run and experiment.

Example 1: Very basic example of converting a struct to yaml.

package main

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

type Student struct {
    Name string
    Age  int
}

func main() {
    s1 := Student{
        Name: "Sagar",
        Age:  23,
    }

    yamlData, err := yaml.Marshal(&s1)

    if err != nil {
        fmt.Printf("Error while Marshaling. %v", err)
    }

    fmt.Println(" --- YAML ---")
    fmt.Println(string(yamlData))  // yamlData will be in bytes. So converting it to string.
}
Enter fullscreen mode Exit fullscreen mode

Output:

PS D:\Programming Languages\Go\src\yaml_conversion> go run .\main.go
 --- YAML ---
name: Sagar
age: 23 
Enter fullscreen mode Exit fullscreen mode

Example 2: Providing custom tags.

Let's say we want to have different key names in output yaml. Then we can do that by adding tags. This very similar to JSON tags.

package main

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

type Student struct {
    Name string `yaml:"student-name"`
    Age  int    `yaml:"student-age"`
}

func main() {
    s1 := Student{
        Name: "Sagar",
        Age:  23,
    }

    yamlData, err := yaml.Marshal(&s1)
    if err != nil {
        fmt.Printf("Error while Marshaling. %v", err)
    }

    fmt.Println(" --- YAML with custom tags---")
    fmt.Println(string(yamlData))
}

Enter fullscreen mode Exit fullscreen mode

Output:

PS D:\Programming Languages\Go\src\yaml_conversion> go run .\main.go
 --- YAML with custom tags---
student-name: Sagar
student-age: 23
Enter fullscreen mode Exit fullscreen mode

Tip: Make sure there is no gap between yaml: and "tag". (Wasted 30 mins of my time to figure out why tags are not coming in output)

Example 3: Structure with Arrays and Maps.

Here I have used another structure to store marks. A simple map also works.

package main

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

type MarksStruct struct {
    Sceince     int8 `yaml:"science"`
    Mathematics int8 `yaml:"mathematics"`
    English     int8 `yaml:"english"`
}

type Student struct {
    Name   string      `yaml:"student-name"`
    Age    int8        `yaml:"student-age"`
    Marks  MarksStruct `yaml:"subject-marks"`
    Sports []string
}

func main() {
    s1 := Student{
        Name: "Sagar",
        Age:  23,
        Marks: MarksStruct{
            Sceince:     95,
            Mathematics: 90,
            English:     90,
        },
        Sports: []string{"Cricket", "Football"},
    }

    yamlData, err := yaml.Marshal(&s1)

    if err != nil {
        fmt.Printf("Error while Marshaling. %v", err)
    }

    fmt.Println(" --- YAML with maps and arrays ---")
    fmt.Println(string(yamlData))
}

Enter fullscreen mode Exit fullscreen mode

Output:

PS D:\Programming Languages\Go\src\yaml_conversion> go run .\main.go
 --- YAML with maps and arrays ---
student-name: Sagar
student-age: 23
subject-marks:
  science: 95
  mathematics: 90
  english: 90
sports:
- Cricket
- Football
Enter fullscreen mode Exit fullscreen mode

Example 4: Sometimes we want to actually create a YAML file.

package main
import (
    "fmt"
    "io/ioutil"

    "gopkg.in/yaml.v2"
)

type MarksStruct struct {
    Sceince     int8 `yaml:"science"`
    Mathematics int8 `yaml:"mathematics"`
    English     int8 `yaml:"english"`
}

type Student struct {
    Name   string      `yaml:"student-name"`
    Age    int8        `yaml:"student-age"`
    Marks  MarksStruct `yaml:"subject-marks"`
    Sports []string
}

func main() {
    s1 := Student{
        Name: "Sagar",
        Age:  23,
        Marks: MarksStruct{
            Sceince:     95,
            Mathematics: 90,
            English:     90,
        },
        Sports: []string{"Cricket", "Football"},
    }

    yamlData, err := yaml.Marshal(&s1)

    if err != nil {
        fmt.Printf("Error while Marshaling. %v", err)
    }

    fileName := "test.yaml"
    err = ioutil.WriteFile(fileName, yamlData, 0644)
    if err != nil {
        panic("Unable to write data into the file")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output will be a file named test.yaml file.

Thank you for reading. Hope this helps.

Discussion (0)