gpt4 book ai didi

go - 无法解码嵌套的Yaml

转载 作者:行者123 更新时间:2023-12-01 22:15:57 36 4
gpt4 key购买 nike

Yaml输入:

Tasks:
- task:
name: 123
retry: 5
next: 123
- task:
name: 123
retry: 5
next: 123

码:
package main

import (
"fmt"
"io/ioutil"
"os"

"gopkg.in/yaml.v2"
)

type Tasks []struct {
Task Task `yaml:"task"`
}

type Task struct {
Name string `yaml:"name"`
Retry int `yaml:"retry"`
Next string `yaml:"next"`
}

func main() {
var w Tasks
wfyaml, _ := os.Open(".yaml")
byteValue, _ := ioutil.ReadAll(wfyaml)
yaml.Unmarshal(byteValue, &w)
fmt.Printf("%+v\n", w)
}

输出:[]

我不知道是什么原因造成的。我已经检查了我能做的。

最佳答案

您错过了结构(playground)中的顶层(Tasks):

package main

import (
"fmt"

"gopkg.in/yaml.v2"
)

const yamlStr = `Tasks:
- task:
name: 123
retry: 5
next: 123
- task:
name: 123
retry: 5
next: 123`

type File struct {
Tasks Tasks `yaml:"Tasks"`
}

type Tasks []struct {
Task Task `yaml:"task"`
}

type Task struct {
Name string `yaml:"name"`
Retry int `yaml:"retry"`
Next string `yaml:"next"`
}

func main() {
var w File
yaml.Unmarshal([]byte(yamlStr), &w)
fmt.Printf("%+v\n", w)
}

关于go - 无法解码嵌套的Yaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60222480/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com