英文:
golang parse yaml file struct challenged
问题
遇到了解析这种类型的YAML文件的问题。使用"yaml.v2"库。
info: "abc"
data:
source: http://intra
destination: /tmp
run:
- id: "A1"
exe: "run.a1"
output: "output.A1"
- id: "A2"
exe: "run.a2"
output: "output.A2"
我想要获取YAML文件的所有值,以便有一个基本的结构体如下:
type Config struct {
Info string
Data struct {
Source string `yaml:"source"`
Destination string `yaml:"destination"`
}
}
这部分是可以工作的。
但是,我不确定如何为"run"设置结构体。额外的层级让我感到困惑。
type Run struct {
...
}
英文:
Having a problem parsing this sort of yaml file. Using "yaml.v2"
info: "abc"
data:
source: http://intra
destination: /tmp
run:
- id: "A1"
exe: "run.a1"
output: "output.A1"
- id: "A2"
exe: "run.a2"
output: "output.A2"
I would like to get all the values of the YAML file so I have a basic struct like this
type Config struct {
Info string
Data struct {
Source string `yaml:"source"`
Destination string `yaml:"destination"`
}
}
This works
But, I am not sure how to setup the struct for "run". The extra layer is confusing me.
type Run struct {
...
}
答案1
得分: 1
OP的YAML示例是无效的。当run
的值是字典列表时,应该像这样:
info: "abc"
data:
source: http://intra
destination: /tmp
run:
- id: "A1"
exe: "run.a1"
output: "output.A1"
- id: "A2"
exe: "run.a2"
output: "output.A2"
以下是相应的数据结构和将YAML解码为golang结构的示例:
package main
import (
"fmt"
"io/ioutil"
"os"
yaml "gopkg.in/yaml.v2"
)
type Config struct {
Info string
Data struct {
Source string
Destination string
}
Run []struct {
Id string
Exe string
Output string
}
}
func main() {
var conf Config
reader, _ := os.Open("example.yaml")
buf, _ := ioutil.ReadAll(reader)
yaml.Unmarshal(buf, &conf)
fmt.Printf("%+v\n", conf)
}
运行此代码将输出(为了可读性添加了一些缩进):
{
Info: "abc",
Data: {
Source: "http://intra",
Destination: "/tmp"
},
Run: [
{
Id: "A1",
Exe: "run.a1",
Output: "output.A1"
},
{
Id: "A2",
Exe: "run.a2",
Output: "output.A2"
}
]
}
英文:
the OP's example of YAML is invalid. When value of run
is list of dictionary it should be something like this:
<!-- language: lang-none -->
info: "abc"
data:
source: http://intra
destination: /tmp
run:
- id: "A1"
exe: "run.a1"
output: "output.A1"
- id: "A2"
exe: "run.a2"
output: "output.A2"
And here's the corresponding data struture, and example for decoding YAML into golang's structure.
<!-- language: language-none -->
package main
import (
"fmt"
"io/ioutil"
"os"
yaml "gopkg.in/yaml.v2"
)
type Config struct {
Info string
Data struct {
Source string
Destination string
}
Run []struct {
Id string
Exe string
Output string
}
}
func main() {
var conf Config
reader, _ := os.Open("example.yaml")
buf, _ := ioutil.ReadAll(reader)
yaml.Unmarshal(buf, &conf)
fmt.Printf("%+v\n", conf)
}
running this will output (added some indent for readability):
<!-- language: lang-none -->
{Info:abc
Data:{Source:http://intra Destination:/tmp}
Run:[{Id:A1 Exe:run.a1 Output:output.A1}
{Id:A2 Exe:run.a2 Output:output.A2}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论