2016-09-24 41 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