Sling Academy
Home/Golang/How to Work with YAML in Go Using `go-yaml`

How to Work with YAML in Go Using `go-yaml`

Last updated: November 27, 2024

YAML is a human-friendly data serialization standard that is widely used for configuration files and data exchange between programming languages. In Go, the gopkg.in/yaml.v3 package, commonly referred to as `go-yaml`, is a popular library used to encode and decode YAML data structures.

Installing the `go-yaml` Package

To start working with YAML in Go, you first need to install the `go-yaml` package. You can do this using the Go package manager. Run the following command in your terminal:

go get gopkg.in/yaml.v3

Reading YAML Data

Let's suppose you have the following YAML content that you want to parse into a Go struct:

name: John Doe
age: 30
email: [email protected]

First, define a Go struct that mirrors the structure of your YAML file:

type Person struct {
    Name  string `yaml:"name"`
    Age   int    `yaml:"age"`
    Email string `yaml:"email"`
}

Now, decode the YAML content into this struct:

package main

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

func main() {
    yamlData := []byte(`name: John Doe
age: 30
email: [email protected]`)

    var person Person

    err := yaml.Unmarshal(yamlData, &person)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("Parsed Struct: %+v
", person)
}

Writing YAML Data

Suppose you want to write a Go struct back to YAML. Below is an example of how to encode a Go struct into YAML:

package main

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

type Person struct {
    Name  string `yaml:"name"`
    Age   int    `yaml:"age"`
    Email string `yaml:"email"`
}

func main() {
    person := Person{Name: "Jane Doe", Age: 25, Email: "[email protected]"}

    yamlData, err := yaml.Marshal(&person)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Println(string(yamlData))
}

Handling Complex YAML Structures

When dealing with more complex structures including nested data, `go-yaml` can also handle these elegantly. Here is how you could manage more complex data:

yamlContent:  
  jobs:
    - name: Build
      script: make build
    - name: Test
      script: make test

Map the YAML to a Go struct:

type Job struct {
    Name   string `yaml:"name"`
    Script string `yaml:"script"`
}

type Config struct {
    Jobs []Job `yaml:"jobs"`
}

func main() {
    yamlData := []byte(`yamlContent: 
 jobs:
 - name: Build
 script: make build
 - name: Test
 script: make test`)

    var config Config
    err := yaml.Unmarshal(yamlData, &config)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("Parsed Config: %+v
", config)
}

These examples demonstrate basic usage of the `go-yaml` library. Knowing how to both read and write YAML in Go can greatly enhance your capability to manage configuration files in a scalable and human-readable format.

 

Next Article: Parsing Command-Line Flags with the `flag` Package in Go

Previous Article: Building CLI Tools with the `cobra` Package in Go

Series: Go Utilities and Tools

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant