开始读取YAML文件并映射到结构片 [英] GO reading YAML file and mapping to slice of structs
问题描述
我正在尝试使用GO读取YAML文件并将其映射到我定义的结构. YAML如下:
I'm attempting to read a YAML file using GO and mapping it to a structure that I've defined. 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"
我使用以下代码来读取文件Unmarshal数据,然后打印一些数据.
I used the following code to read in the file, Unmarshal the data, and then print some of the data.
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)
工作,显示引用及其数据.但是,下一行未能说明索引超出范围.这是错误:
When I run this, the first fmt.Println(time_data)
works, showing the reference and its data. The next line though fails saying that the index is out of range. 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中,并
I then thought maybe my YAML wasn't formatted properly, so I loaded the YAML file into Ruby's IRB, and 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隐藏了很多内容.
The IRB output shows that my YAML is formatted properly, however, I don't think I'm Unmarshalling it properly then. However, I'm not sure what I would need to do to get this to work. I'm sure I'm not thinking of how to do this properly since Ruby hides a lot of it.
推荐答案
首先,通过在
err = yaml.Unmarshal(gtt_config, &td)
您将得到相应的错误,即 time parsing error
. yaml
解码器的预期时间为 RFC3339 格式.有几种方法可以解决此问题:
you will get the corresponding error which is time parsing error
. The yaml
decoder expect time in RFC3339 format. There are several ways to fix this:
- 将YAML文件中的时间数据更改为RFC3339格式,例如
"2012-10-31T15:50:13.793654Z"
- 如果您无法修改YAML文件,则需要实现自定义解码器.
对于(2),我想到了两个解决方案:
For (2), two solutions come to my mind:
- 实施
yaml.Unmarshaler
界面,或 - 将
time.Time
包装为自定义类型,然后实现encoding.TextUnmarshaler
接口
- Implement
yaml.Unmarshaler
interface, or - Wrap
time.Time
to a custom type then implementencoding.TextUnmarshaler
interface
解决方案(1):您需要为 Date_File
和 Time_Data
类型实现自定义Unmarshaler.将以下内容添加到您的源代码中.
Solution (1): You need to implement custom Unmarshaler for Date_File
and Time_Data
types. Add the following to your source code.
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
字段的 types
,则解决方案(1)可能不切实际.
If you have many types
having time.Time
field, solution (1) maybe impractical.
解决方案(2):如果您查看 yaml解码器,它依靠 TextUnmarshaler
将字符串转换为相应的类型.在这里您需要:
Solution (2): If you look at source code of yaml decoder, it rely on TextUnmarshaler
to convert string to corresponding type. Here you need to:
- 定义自定义时间类型(例如
CustomTime
) - 用
CustomTime
替换结构中的每个 - 实施
UnmarshalText
time.Time
字段(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()
}
这篇关于开始读取YAML文件并映射到结构片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!