2016-09-24 39 views
0

我正在嘗試使用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隱藏了很多,我確信我沒有考慮如何正確地做到這一點。

+0

差不多,@putu回答解決了我的問題。 – Pred

回答

3

首先,通過後

err = yaml.Unmarshal(gtt_config, &td) 

添加checkerr(err)你會得到相應的錯誤是time parsing erroryaml解碼器預計時間格式爲RFC3339。有幾種方法可以解決此問題:

  1. 將YAML文件中的時間數據更改爲RFC3339格式,例如, "2012-10-31T15:50:13.793654Z"
  2. 如果你不能修改YAML文件,你需要實現自定義解碼器。

對於(2),兩種解決方案來我的腦海:

  1. 實現yaml.Unmarshaler接口,或
  2. time.Time到自定義類型,然後實現encoding.TextUnmarshaler接口

解決方案( 1):您需要爲Date_FileTime_Data類型實現自定義的Unmarshaler。將以下內容添加到您的源代碼中。

func (df *Date_File) UnmarshalYAML(unmarshal func(interface{}) error) error { 
    //Unmarshal time to string then convert to time.Time manually 
    var tmp struct { 
     Owner string  `yaml:"owner"` 
     Init  string  `yaml:"initialized"` 
     TimeData []Time_Data `yaml:"time_data"` 
    } 
    if err := unmarshal(&tmp); err != nil { 
     return err; 
    } 

    const layout = "2006-01-02 15:04:05.999999999 -0700 MST" 
    tm, err := time.Parse(layout, tmp.Init) 
    if err != nil { 
     return err 
    } 

    df.Owner = tmp.Owner 
    df.Init  = tm 
    df.TimeData = tmp.TimeData 

    return nil 
} 

func (td *Time_Data) UnmarshalYAML(unmarshal func(interface{}) error) error { 
    //Unmarshal time to string then convert to time.Time manually 
    var tmp struct { 
     Action string `yaml:"action"` 
     Time string `yaml:"time"` 
    } 
    if err := unmarshal(&tmp); err != nil { 
     return err; 
    } 

    const layout = "2006-01-02 15:04:05.999999999 -0700 MST" 
    tm, err := time.Parse(layout, tmp.Time) 
    if err != nil { 
     return err 
    } 

    td.Action = tmp.Action 
    td.Time = tm 

    return nil 
} 

如果你有time.Time領域,解決方案(1)也許不切實際的許多types。解決方案(2):如果您查看yaml decoder的源代碼,則依靠TextUnmarshaler將字符串轉換爲相應的類型。您需要:

  1. 定義自定義時間類型(例如,CustomTime
  2. 替換每個time.Time場在你的結構與CustomTime
  3. 實施UnmarshalText

爲(3)的片段:

type CustomTime struct { 
    time.Time 
} 
func (tm *CustomTime) UnmarshalText(text []byte) error { 
    const layout = "2006-01-02 15:04:05.999999999 -0700 MST" 
    tmValue, err := time.Parse(layout, string(text)) 
    if err != nil { 
     return err 
    } 

    tm.Time = tmValue 
    return nil  
} 
//Not directly related, for print function etc. 
func (tm CustomTime) String() string { 
    return tm.Time.String() 
} 
+0

我不能相信改變我的時間格式是讓我無法讓這個工作。謝謝。我不知道RFC3339文檔。謝謝普圖 – Pred