duanlu1950 2019-03-05 14:16
浏览 550
已采纳

用密钥解析Yaml提供错误

I’ve the following yaml which I need to parse, I’ve tried with the following


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

  after: test2
     - value: bbb
        - aaa: aaaa


I’ve tried with the following:

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"`
 }

Now when I parse it I got error,

What I need is to get the values from the object before and after which are hardcoded value in the yaml And all the others value under it are dynmically can be added therefor I put it as interface

btw, if I change the root to this its working and I see all the fields under the Build-t but the before and after are like keys ...

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

the error is:

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

see the yaml valid here https://codebeautify.org/yaml-validator/cb705458

  • 写回答

1条回答 默认 最新

  • douhuan3420 2019-03-05 14:30
    关注

    That sounds correct - the YAML is invalid. Did you mean something like this?

    Build-t:
     before:
       test1:
         - value: dddd
         - bbb: zzzz
    
     after:
       test2:
         - value: bbb
         - aaa: aaaa
    

    Remember that the whitespace is important, and it's a key-value structure - so your values can either be strings, or substructures - not both.

    Also, that yaml validator... I can't seem to make it declare anything as invalid!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?