【问题标题】:GO reading YAML file and mapping to slice of structsGO 读取 YAML 文件并映射到结构切片
【发布时间】:2016-09-24 20:02:01
【问题描述】:

我正在尝试使用 GO 读取 YAML 文件并将其映射到我定义的结构。 The YAML is below

--- # 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 的回答解决了我的问题。

标签: go yaml


【解决方案1】:

首先,通过在

之后添加checkerr(err)
err = yaml.Unmarshal(gtt_config, &td)

你会得到相应的错误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
}

如果您有很多 types 具有 time.Time 字段,则解决方案 (1) 可能不切实际。

解决方案(2):如果查看yaml decoder的源代码,它依赖TextUnmarshaler将字符串转换为相应的类型。在这里你需要:

  1. 定义自定义时间类型(例如CustomTime
  2. 将结构中的每个time.Time 字段替换为CustomTime
  3. 实施UnmarshalText

(3) 的 sn-p:

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()
}

【讨论】:

  • 我不敢相信改变我的时间格式是让我无法让它工作的原因。谢谢你。我不知道 RFC3339 文档。谢谢普图
猜你喜欢
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2018-12-05
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多