在Go 中解析YAML 檔案
問題:
問題:--- firewall_network_rules: rule1: src: blablabla-host dst: blabla-hostname ...
您在解析Go 中的您在解析Go 中的分析YAML 檔案。以下是您嘗試解析的範例YAML 檔案:
解決方案:type FirewallNetworkRule struct { Src string `yaml:"src"` Dst string `yaml:"dst"` } type Config struct { FirewallNetworkRules map[string][]FirewallNetworkRule `yaml:"firewall_network_rules"` }
var config Config err := yaml.Unmarshal(yamlFile, &config) if err != nil { panic(err) } fmt.Printf("Value: %#v\n", config.FirewallNetworkRules)
現在,要將YAML 檔案解組到Config 結構中,請使用以下程式碼:
進階範例: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"` }
var service Service err := yaml.Unmarshal(yourFile, &service) if err != nil { panic(err) } fmt.Print(service.Metadata.Name)
以上是如何在 Go 中有效解析複雜的 YAML 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!