doukui4836 2017-08-22 17:52
浏览 427
已采纳

找出正确的结构来解析Golang中的简单YAML文件

I have a fairly simple YAML document to parse into a (preferably) map in Go.

YAML doc:

---
A: Logon
'0': Heartbeat
'1': Test Request
'2': Resend Request
'3': Reject
'4': Sequence Reset
'5': Logout
'8': Execution Report
S: Quote
AE: Trade Capture Report
B: News
h: Trading Session Status
f: Security Status

I'm trying to marshal it with

type TranslationVal struct {
    Map map[string]string
}

translationVal := TranslationVal{}
err := yaml.Unmarshal([]byte(val), &translationVal)

However I'm getting:

2017/08/22 20:33:23 yaml: unmarshal errors:   line 1: cannot unmarshal !!str `A` into main.TranslationVal
  • 写回答

2条回答 默认 最新

  • dougou1943 2017-08-22 17:56
    关注

    The issue is caused by you wrapping the map in an object, the YAML has no such nesting.

    map := map[string]string{}
    err := yaml.Unmarshal([]byte(val), &map)
    

    You can actually just unmarshal directly into the map itself

    EDIT: hard to tell with your formatting but if those integer keys are nested under A then you will need a different structure as well, it would actually be a map[string]map[string]string -- however that is rather ugly so I would recommend moving to a different paradigm at that point... You could either use a map[string]interface{} which wouldn't care what types go into the map and then you could deal with it later or you could define the object more statically, using actually keys such a A in a struct to denote where each item goes, if that were the case you'd have an object like the following;

    type TranslationVal struct {
        A map[string]string
        B string
        C string
        // and so on
        F string `yaml:f` // necessary because f would be unexported
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大