我正在尝试使用 Go 解析 yaml 文件。不幸的是,我无法弄清楚如何。我的yaml文件是这样的:
---
firewall_network_rules:
rule1:
src: blablabla-host
dst: blabla-hostname
...
我有这个 Go 代码,但它不起作用:
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
"gopkg.in/yaml.v2"
)
type Config struct {
Firewall_network_rules map[string][]string
}
func main() {
filename, _ := filepath.Abs("./fruits.yml")
yamlFile, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
var config Config
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
panic(err)
}
fmt.Printf("Value: %#v\n", config.Firewall_network_rules)
}
当我运行它时,我得到一个错误。我认为这是因为我还没有为 src 和 dst 键/值创建结构。仅供引用:当我将其更改为列表时,它可以工作。
所以上面的代码会解析这个:
---
firewall_network_rules:
rule1:
- value1
- value2
...
最佳答案
如果您更具体地使用 google cloud 或 kubernetes,并希望像这样解析 service.yaml:
apiVersion: v1
kind: Service
metadata:
name: myName
namespace: default
labels:
router.deis.io/routable: "true"
annotations:
router.deis.io/domains: ""
spec:
type: NodePort
selector:
app: myName
ports:
- name: http
port: 80
targetPort: 80
- name: https
port: 443
targetPort: 443
提供一个真实世界的示例,以便您了解如何编写嵌套。
type Service struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
Namespace string `yaml:"namespace"`
Labels struct {
RouterDeisIoRoutable string `yaml:"router.deis.io/routable"`
} `yaml:"labels"`
Annotations struct {
RouterDeisIoDomains string `yaml:"router.deis.io/domains"`
} `yaml:"annotations"`
} `yaml:"metadata"`
Spec struct {
Type string `yaml:"type"`
Selector struct {
App string `yaml:"app"`
} `yaml:"selector"`
Ports []struct {
Name string `yaml:"name"`
Port int `yaml:"port"`
TargetPort int `yaml:"targetPort"`
NodePort int `yaml:"nodePort,omitempty"`
} `yaml:"ports"`
} `yaml:"spec"`
}
有一个方便的服务叫做 yaml-to-go https://zhwt.github.io/yaml-to-go/它将 YAML 转换为 go 结构,只需将您的 YAML 输入到该服务中,您就会得到一个自动生成的结构。
同样存在 JSON 等价物:https://mholt.github.io/json-to-go/
最后解码,正如之前的海报所写:
var service Service
err = yaml.Unmarshal(yourFile, &service)
if err != nil {
panic(err)
}
fmt.Print(service.Metadata.Name)
关于struct - 去解析yaml文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28682439/