我有多个需要解析且结构完全相同的yaml文件
schema: "1.0.0"
id: test
version: "1.2.3"
dependency :
- name: ui
type: runner
cwd: /ui
install:
- name: api
group: test
properties:
name: app
url: appUrl
- name: backend
type: mongoDb
path: be
install:
- name: db
type: mongo
provides:
- name: api
properties:
url: url
The schema section is mandatory for all the yaml which the app should get always
The dependency tag can contain 1..n entries with mandatory fields ,name, type, cwd
The dependency tag can (or not) contain
install
section withname
andproperties
which is mandatoryThe dependency tag can (or not) contain
provides
section withname
and which is mandatoryThe install can have properties and the provides also can have properties
我正在使用 yaml parser解析文件,但我的问题是如何在 Golang 中构建结构,当我解析文档时它会自动填充主结构并将包括子结构(例如依赖项/安装部分)
我试过类似的东西
type main struct {
schema struct {
schema string
id int
version string
}
dependency struct {
name string
type string
cwd string
install struct {
name string
}
}
在安装部分,它可以是组或类型或两者,它也可以有属性部分,所以我不确定如何构建 我用来解析文档的一些通用/可扩展结构(文档具有接近的属性列表,我在示例中描述的内容描述了最多的选项)
我用这个库来解析文档
最佳答案
你的结构定义应该是这样的
type Yaml struct {
Schema string
ID string
Version string
Dependency []Dependency
}
type Dependency struct {
Name string
Type string
CWD string
Install []Install
Provides []Provide
}
type Install struct {
Name string
Group string
Type string
Properties Properties
}
type Properties struct {
Name string
URL string
}
type Provide struct {
Name string
Properties Properties
}
这是完整的示例代码:
package main
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
)
var data = `
schema: "1.0.0"
id: test
version: "1.2.3"
dependency :
- name: ui
type: runner
cwd: /ui
install:
- name: api
group: test
properties:
name: app
url: appUrl
- name: backend
type: mongoDb
path: be
install:
- name: db
type: mongo
provides:
- name: api
properties:
url: url
`
type Yaml struct {
Schema string
ID string
Version string
Dependency []Dependency
}
type Dependency struct {
Name string
Type string
CWD string
Install []Install
Provides []Provide
}
type Install struct {
Name string
Group string
Type string
Properties Properties
}
type Properties struct {
Name string
URL string
}
type Provide struct {
Name string
Properties Properties
}
func main() {
y := Yaml{}
err := yaml.Unmarshal([]byte(data), &y)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%+v\n", y)
}
输出
{Schema:1.0.0 ID:test Version:1.2.3 Dependency:[{Name:ui Type:runner CWD:/ui Install:[{Name:api Group:test Type: Properties:{Name:appURL:appUrl}}] Provides:[]} {Name:backend Type:mongoDb CWD: Install:[{Name:db Group: Type:mongo Properties:{Name: URL:}}] Provides:[{Name:api Properties:{Name: URL:url}}]}]}
如果你想从 yaml 文件中读取,在 main func 中只需替换:
err := yaml.Unmarshal([]byte(data), &y)
与
yamlFile, err := ioutil.ReadFile("yaml_sample.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, &y)
关于go - 将 yaml 文件解析为 go 中的预定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47750076/