"Go YAML 파일 Unmarshal"의 두 판 사이의 차이

 
104번째 줄: 104번째 줄:
* [[Go YAML 파일 여러 문서 Unmarshal]]
* [[Go YAML 파일 여러 문서 Unmarshal]]


[[분류: Go]]
[[분류: Go YAML]]
[[분류: YAML]]
[[분류: .yaml]]
[[분류: .yaml]]

2023년 1월 19일 (목) 22:00 기준 최신판

1 개요[ | ]

Go YAML 파일 Unmarshal

2 단일 문서[ | ]

id: 1
name: Reds
colors:
- Crimson
- Red
- Ruby
- Maroon
package main

import (
	"fmt"
	"io/ioutil"

	"gopkg.in/yaml.v3"
)

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

func main() {
	yamlBytes, err := ioutil.ReadFile("a.yaml")
	if err != nil {
		fmt.Println("ReadFile error:", err)
		return
	}
	var cg ColorGroup
	err = yaml.Unmarshal(yamlBytes, &cg)
	if err != nil {
		fmt.Println("Unmarshal error:", err)
		return
	}
	fmt.Printf("%+v", cg)
}

3 여러 문서[ | ]

---
name: Ed
text: Knock knock.
---
name: Sam
text: Who's there?
---
name: Ed
text: Go fmt.
---
name: Sam
text: Go fmt who?
---
name: Ed
text: Go fmt yourself!
package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"gopkg.in/yaml.v3"
)

type Message struct {
	Name string `yaml:"name"`
	Text string `yaml:"text"`
}

func main() {
	f, err := os.Open("messages.yaml")
	if err != nil {
		panic(err)
	}
	dec := yaml.NewDecoder(f)
	for {
		var m Message
		if err := dec.Decode(&m); err == io.EOF {
			break
		} else if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%+v\n", m)
	}
}

4 같이 보기[ | ]

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