Go YAML Unmarshal

(Go YAML Unmarshal()에서 넘어옴)

1 개요[ | ]

Go YAML Unmarshal()
  • YAML → 구조체

2 예시: ColorGroup[ | ]

package main

import (
	"fmt"

	"gopkg.in/yaml.v3"
)

type ColorGroup struct {
	ID     int
	Name   string
	Colors []string
}

func main() {
	var bytes = []byte(`
id: 1
name: Reds
colors:
- Crimson
- Red
- Ruby
- Maroon
`)
	var colorGroup ColorGroup
	err := yaml.Unmarshal(bytes, &colorGroup)
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v", colorGroup)
}

3 예시: Animals[ | ]

package main

import (
	"fmt"

	"gopkg.in/yaml.v3"
)

type Animal struct {
	Name  string
	Order string
}

func main() {
	var bytes = []byte(`
- name: Platypus
  order: Monotremata
- name: Quoll
  order: Dasyuromorphia
`)
	var animals []Animal
	err := yaml.Unmarshal(bytes, &animals)
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v", animals)
}

4 구조체 슬라이스 Rules[ | ]

package main

import (
	"fmt"
	"log"

	"gopkg.in/yaml.v3"
)

type Rule struct {
	APIGroups       []string `yaml:"apiGroups"`
	Resources       []string `yaml:"resources"`
	ResourceNames   []string `yaml:"resourceNames"`
	NonResourceURLs []string `yaml:"nonResourceURLs"`
	Verbs           []string `yaml:"verbs"`
}
type Rules []Rule

var data = `
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["coordination.k8s.io"]
  resourceNames: ["kube-scheduler"]
  resources: ["leases"]
  verbs: ["get", "update"]
- nonResourceURLs: ["/metrics"]
  verbs: ["get"]
`

func main() {
	rules := Rules{}
	err := yaml.Unmarshal([]byte(data), &rules)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("%+v\n", rules)
}

5 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}