TAKEO

TAKEO

GoでYamlを扱う

まとめ

  • Yamlを構造体に変換する
  • 構造体をYamlに変換する

gopkg.in/yaml.v3は外部パッケージなので以下が必要になる。

Copied!!
$ go get gopkg.in/yaml.v3

実装例

example.go
Copied!!
package main

import (
	"fmt"
	"log"

	"gopkg.in/yaml.v3"
)

// Person is a struct that represents a person with a Name and Age
type Person struct {
	Name     string `yaml:"name"`
	Age      int    `yaml:"age"`
	Birthday string `yaml:"birth"`
}

type Persons []Person

func main() {
	yamlData := `
name: Alice
age: 30
birth: 1994/01/01
`

	var person Person
	err := yaml.Unmarshal([]byte(yamlData), &person)
	if err != nil {
		log.Fatalf("Error converting yaml to struct: %v", err)
	}

	fmt.Printf("Struct: %+v\n", person)

	newYamlData, err := yaml.Marshal(person)
	if err != nil {
		log.Fatalf("Error converting struct to YAML: %v", err)
	}

	fmt.Printf("YAML:\n%s\n", newYamlData)

	yamlArray := `[{"name": "Alice", "age": 30, "birth": "1994/03/03"},{"name": "Hikaru", "age": 25, "birth": "1999/01/01"}]`

	var persons Persons
	err = yaml.Unmarshal([]byte(yamlArray), &persons)
	if err != nil {
		log.Fatalf("Error converting YAML to struct: %v", err)
	}
	fmt.Printf("List of struct: %+v\n", persons)

	newYamlArray, err := yaml.Marshal(persons)
	if err != nil {
		log.Fatalf("Error converting struct to YAML: %v", err)
	}

	fmt.Printf("YAML:\n%s\n", newYamlArray)
}