去解析yaml文件

新手上路,请多包涵

我正在尝试用 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
...

原文由 Rogier Lommers 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 901
1 个回答

如果您更具体地使用谷歌云或 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)

原文由 JazzCat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏