【问题标题】:Parse yaml with keys provide errors使用键解析 yaml 提供错误
【发布时间】:2019-03-05 14:16:30
【问题描述】:

我有以下需要解析的 yaml, 我已经尝试了以下


Build-t:
  before: test1
    - value : dddd 
       -  bbb: zzzz

  after: test2
     - value: bbb
        - aaa: aaaa


我尝试了以下方法:

type root struct{
 build type Build `yaml:"Build-t,omitempty"`
} 


type Build struct {
    Before map[string]interface{} `yaml:"before,omitempty"`
    After map[string]interface{} `yaml:"after,omitempty"`
 }

现在当我解析它时,我得到了错误,

我需要的是从对象 beforeafter 中获取值,它们是 yaml 中的硬编码值 并且它下面的所有其他值都可以动态添加,因此我将其命名为interface

顺便说一句,如果我将根更改为此它的工作并且我看到Build-t 下的所有字段但before and after 就像键...

type root struct{
 build type map[string]interface{} `yaml:"Build-t,omitempty"`
} 

错误是:

line 6: cannot unmarshal !!str `test1` into map[string]interface {}
        line 7: cannot unmarshal !!str `test2` into map[string]interface {}

在此处查看有效的 yaml https://codebeautify.org/yaml-validator/cb705458

【问题讨论】:

  • 您所说的“我遇到错误”是什么意思 - 是否有任何错误消息可以分享?
  • @NicoHaase - 当然,请查看我的更新
  • 您的 YAML 示例首先看起来不像是有效的 YAML。
  • @Iguananaut - 请查看我的更新
  • 永远不要在 codebeautify.com 上使用“验证器”,它接受一些无效的 YAML,并拒绝一些完美的 YAML。

标签: go yaml


【解决方案1】:

听起来很正确 - YAML 无效。你的意思是这样的吗?

Build-t:
 before:
   test1:
     - value: dddd
     - bbb: zzzz

 after:
   test2:
     - value: bbb
     - aaa: aaaa

请记住,空格很重要,它是一个键值结构 - 因此您的值可以是字符串或子结构 - 不能同时是两者。

另外,那个 yaml 验证器...我似乎无法让它声明任何内容为无效!

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 1970-01-01
    • 2014-02-03
    • 2019-01-20
    • 2016-10-26
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多