我正在嘗試使用GO讀取YAML文件並將其映射到我已定義的結構。 The YAML is below:去閱讀YAML文件和映射到結構片
--- # go_time_tracker.yml
owner: "Phillip Dudley"
initialized: "2012-10-31 15:50:13.793654 +0000 UTC"
time_data:
- action: "start"
time: "2012-10-31 15:50:13.793654 +0000 UTC"
- action: "stop"
time: "2012-10-31 16:00:00.000000 +0000 UTC"
我用the following code在文件中讀取,解組數據,然後打印一些數據。
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"time"
)
type Date_File struct {
Owner string `yaml:"owner"`
Init time.Time `yaml:"initialized"`
TimeData []Time_Data `yaml:"time_data"`
}
type Time_Data struct {
//
Action string `yaml:"action"`
Time time.Time `yaml:"time"`
}
func checkerr(err error) {
if err != nil {
log.Fatal(err)
}
}
func read() (td *Date_File) {
//td := &Date_File{}
gtt_config, err := ioutil.ReadFile("go_time_tracker.yml")
checkerr(err)
err = yaml.Unmarshal(gtt_config, &td)
return td
}
func main() {
//
time_data := read()
fmt.Println(time_data)
fmt.Println(time_data.TimeData[0])
fmt.Println(time_data.Owner)
}
當我運行此,第一fmt.Println(time_data)
作品,顯示了參考和它的數據。下一行雖然失敗,說索引超出範圍。 This is the error:
$ go run yaml_practice_2.go
&{Phillip Dudley 0001-01-01 00:00:00 +0000 UTC []}
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0x559840, 0xc82000a0e0)
/usr/lib/go-1.6/src/runtime/panic.go:481 +0x3e6
main.main()
/home/predatorian/Documents/go/src/predatorian/yaml/yaml_practice_2.go:41 +0x2aa
exit status 2
我當時想,也許我是YAML格式不正確,所以我裝了YAML文件轉換成Ruby的IRB和this is what I got。
irb(main):004:0> data2 = YAML.load(File.read("go_time_tracker.yml"))
=> {"owner"=>"Phillip Dudley", "initialized"=>"2012-10-31 15:50:13.793654 +0000 UTC", "time_data"=>[{"action"=>"start", "time"=>"2012-10-31 15:50:13.793654 +0000 UTC"}, {"action"=>"stop", "time"=>"2012-10-31 16:00:00.000000 +0000 UTC"}]}
IRB輸出顯示我的YAML格式正確,但是,我認爲我沒有正確解組。但是,我不確定我需要做些什麼才能使其發揮作用。由於Ruby隱藏了很多,我確信我沒有考慮如何正確地做到這一點。
差不多,@putu回答解決了我的問題。 – Pred