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 quickl…

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.
}

Output:

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



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))
}

Output:

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

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))
}

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



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")
    }
}

Output will be a file named test.yaml file.

Thank you for reading. Hope this helps.


Print Share Comment Cite Upload Translate
APA
SagarTrimukhe | Sciencx (2024-03-28T20:46:55+00:00) » Generate YAML files in Golang.. Retrieved from https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/.
MLA
" » Generate YAML files in Golang.." SagarTrimukhe | Sciencx - Wednesday August 25, 2021, https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/
HARVARD
SagarTrimukhe | Sciencx Wednesday August 25, 2021 » Generate YAML files in Golang.., viewed 2024-03-28T20:46:55+00:00,<https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/>
VANCOUVER
SagarTrimukhe | Sciencx - » Generate YAML files in Golang.. [Internet]. [Accessed 2024-03-28T20:46:55+00:00]. Available from: https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/
CHICAGO
" » Generate YAML files in Golang.." SagarTrimukhe | Sciencx - Accessed 2024-03-28T20:46:55+00:00. https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/
IEEE
" » Generate YAML files in Golang.." SagarTrimukhe | Sciencx [Online]. Available: https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/. [Accessed: 2024-03-28T20:46:55+00:00]
rf:citation
» Generate YAML files in Golang. | SagarTrimukhe | Sciencx | https://www.scien.cx/2021/08/25/generate-yaml-files-in-golang/ | 2024-03-28T20:46:55+00:00
https://github.com/addpipe/simple-recorderjs-demo