はじめに
読み込みたいyaml例
userのデータが入ってると仮定したyamlです
sample.yaml
users: - name: ほげ ほげ男 full_name: first_name: ほげ last_name: ほげ男 sex: male birthday: 1990-12-12 self_introduction: long: ほげほげ男です。よろしくおねがいします! short: しゃす! image_urls: - /my/photo/01.png - /my/photo/02.png - /my/photo/03.png shemale: false - name: ふが ふが子 full_name: first_name: ふが last_name: ふが子 sex: female birthday: 1994-03-03 self_introduction: long: ふが子です!(≧∀≦*) image_urls: - /my/photo/01.png shemale: true
使うパッケージ
gopkg.in/yaml.v2 というパッケージを使います。
go getで取得すればいけるはず
$ go get gopkg.in/yaml.v2
今回はglideで入れました
構成
sample.yaml が読み込みたいyamlです。
glideな関係でmainのコードはsrc/go-yaml-sample/yaml_sample.goとなってます。
$ pwd
プロジェクトdir
$ tree -L 3
.
├── sample.yaml
└── src
└── yaml_sample
├── glide.lock
├── glide.yaml
├── vendor
└── yaml_sample.go
コード
gopkg.in/yaml.v2 を使うと、json.Marshalな感じでyamlを読み込んでくれます。
src/go-yaml-sample/yaml_sample.go
package main import ( "fmt" "io/ioutil" yaml "gopkg.in/yaml.v2" ) // structたち type Data struct { Users []User `yaml:"users"` } type User struct { Name string `yaml:"common"` FullName fullName `yaml:"full_name"` Sex string `yaml:"sex"` SelfIntroduction selfIntroduction `yaml:"self_introduction"` ImageURLs []string `yaml:"image_urls"` Shemale bool `yaml:"shemale"` } type fullName struct { FirstName string `yaml:"first_name"` LastName string `yaml:"last_name"` } type selfIntroduction struct { Long string `yaml:"long"` Short string `yaml:"short"` } func main() { // yamlを読み込む buf, err := ioutil.ReadFile("../../sample.yaml") if err != nil { panic(err) } fmt.Printf("buf: %+v\n", string(buf)) // structにUnmasrshal var d Data err = yaml.Unmarshal(buf, &d) if err != nil { panic(err) } fmt.Printf("d: %+v", d) }
結果
$ cd src/yaml_sample/
$ go run yaml_sample.go
buf: users:
-
name: ほげ ほげ男
full_name:
first_name: ほげ
last_name: ほげ男
sex: male
birthday: 1990-12-12
self_introduction:
long: ほげほげ男です。よろしくおねがいします!
short: しゃす!
image_urls:
- /my/photo/01.png
- /my/photo/02.png
- /my/photo/03.png
shemale: false
-
name: ふが ふが子
full_name:
first_name: ふが
last_name: ふが子
sex: female
birthday: 1994-03-03
self_introduction:
long: ふが子です!(≧∀≦*)
image_urls:
- /my/photo/01.png
shemale: true
d: {Users:[{Name: FullName:{FirstName:ほげ LastName:ほげ男} Sex:male SelfIntroduction:{Long:ほげほげ男です。よろしくおねがいします! Short:しゃす!} ImageURLs:[/my/photo/01.png /my/photo/02.png /my/photo/03.png] Shemale:false} {Name: FullName:{FirstName:ふが LastName:ふが子} Sex:female SelfIntroduction:{Long:ふが子です!(≧∀≦*) Short:} ImageURLs:[/my/photo/01.png] Shemale:true}]}
リポジトリ
おわり
yamlもサクっと簡単!\(^o^)/