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

 
(같은 사용자의 중간 판 4개는 보이지 않습니다)
2번째 줄: 2번째 줄:
;Go YAML 파일 Unmarshal
;Go YAML 파일 Unmarshal


==단일 문서==
<syntaxhighlight lang='yaml' multi=1 file='a.yaml'>
<syntaxhighlight lang='yaml' multi=1 file='a.yaml'>
id: 1
id: 1
18번째 줄: 19번째 줄:
"io/ioutil"
"io/ioutil"


"gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"
)
)


40번째 줄: 41번째 줄:
}
}
fmt.Printf("%+v", cg)
fmt.Printf("%+v", cg)
}
</syntaxhighlight>
==여러 문서==
{{참고|Go YAML 파일 여러 문서 Unmarshal}}
<syntaxhighlight lang='yaml' multi=2 file='messages.yaml'>
---
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!
</syntaxhighlight>
<syntaxhighlight lang='go' multi=2 file='main.go' main>
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)
}
}
}
</syntaxhighlight>
</syntaxhighlight>
47번째 줄: 102번째 줄:
* [[Go YAML Unmarshal]]
* [[Go YAML Unmarshal]]
* [[Go JSON 파일 Unmarshal]]
* [[Go JSON 파일 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 }}