解析yaml结构错误

时间:2018-08-13 15:20:16

标签: go struct yaml

我遇到以下yaml,当我尝试解析它时出现错误,您知道这里可能缺少什么吗?我不确定如何构造zone属性。

T 他是有效的Yaml

https://codebeautify.org/yaml-validator/cb42f23a

错误:

  

模型extConfigYaml中的错误:* yaml:第4行:映射值不正确   在这种情况下允许

type ExternalConfig struct {
    Landscape zone `yaml:"Landscape"`
}


type zone struct {
    zone models `yaml:"zone"`
}

type models struct {
    models []Model `yaml:"models"`
}

type Model struct {
    AppType     string `yaml:"app-type"`
    ServiceType string `yaml:"service-type"`
}

var external_config = []byte(`
Landscape:
  zone: zone1
   models:
    - app-type: app1
      service-type: GCP

    - app-type: app2
      service-type: AMAZON

  zone: zone2
   models:
    - app-type: app3
      service-type: AZURE
    - app-type: app4Í
      service-type: HEROKU
`)


extConfigYaml := ExternalConfig{}

err = yaml.Unmarshal([]byte(external_config), &extConfigYaml)
if err != nil {
    log.Fatalf("error in model extConfigYaml: %v", err)
}
fmt.Printf("%+v\n", extConfigYaml)

1 个答案:

答案 0 :(得分:0)

根据错误:

  

模型extConfigYaml中的错误:* yaml:第4行:映射值不正确   在这种情况下允许

您提供的Yaml内容的缩进出现错误,其中models缩进级别应与zone缩进级别匹配。除此之外,无需为zone创建一个结构,因为它是一个字符串值,但是您已为其分配了一个包含model数据的models结构。另外,您应该使用大写字母导出结构。

将您的代码修改为以下代码:

package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

type ExternalConfig struct {
    Landscape Zone `yaml:"Landscape"`
}

type Zone struct {
    Zone   string  `yaml:"zone"`
    Models []Model `yaml:"models"`
}

type Model struct {
    AppType     string `yaml:"app-type"`
    ServiceType string `yaml:"service-type"`
}

var external_config = []byte(`
Landscape:
  zone: zone1
  models:
    - app-type: app1
      service-type: GCP
    - app-type: app2
      service-type: AMAZON
  zone: zone2
  models:
    - app-type: app3
      service-type: AZURE
    - app-type: app4Í
      service-type: HEROKU
`)

func main() {

    extConfigYaml := ExternalConfig{}

    err := yaml.Unmarshal(external_config, &extConfigYaml)
    if err != nil {
        log.Fatalln("error in model extConfigYaml: %v", err)
    }
    fmt.Printf("%+v\n", extConfigYaml)
}

Playground上的工作代码