duangai1941 2018-12-17 13:16
浏览 70
已采纳

yaml文件中的初始键是任意的,如何在Go中读取它们?

I have the following yaml file

arbitratyKey:
    things:
       - value 1
       - value 2

canBeAnything:
    things:
       - value 1
       - value 2

asdasdasd:
    things:
       - value 1
       - value 2

How do I select a key on this when I am unable to know what the root key will be?

I am using the following library https://godoc.org/gopkg.in/yaml.v2#Unmarshal

Obviously the following code doesn't work, but how do I access the canBeAnything key without specifying a type before?

type T struct{}

t := T{}
yaml.Unmarshal([]byte(data), &t)
fmt.Println(t.canBeAnything)
  • 写回答

1条回答 默认 最新

  • dqwh1209 2018-12-17 13:27
    关注

    In the normal cases, if you are parsing a certain file you would know how it looks ahead of parsing it. So if you know how the file looks, then consider Unmarshaling to an instance of a struct that defines the shape of the file.

    If you don't know the schema and need to work dynamically, Unmarshal into map[string]interface{}

    t := make(map[string]interface{})
    yaml.Unmarshal([]byte(data), &t)
    fmt.Println(t["canBeAnything"])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料