du3979 2016-10-05 19:52
浏览 70

有没有办法确保yaml字符串中的所有数据都已解析?

For testing, I often see go code read byte slices, which are parsed into structs using yaml, for example here:

https://github.com/kubernetes/kubernetes/blob/master/pkg/util/strategicpatch/patch_test.go#L74m

I just got bitten by not exporting my field names, resulting in an empty list which I iterated over in my test cases, thus assuming that all tests were passing (in hindsight, that should have been a red flag :)). There are other errors which are silently ignored by yaml unmarshaling, such as a key being misspelled and not matching a struct field exactly.

Is there a way to ensure that all the data in the byte slice was actually parsed into the struct returned by yaml.Unmarshal? If not, how do others handle this situation?

  • 写回答

1条回答 默认 最新

  • doucang2831 2017-08-20 08:49
    关注

    go-yaml/yaml

    For anyone searching for a solution to this problem, the yaml.v2 library has an UnmarshalStrict method that returns an error if there are keys in the yaml document that have no corresponding fields in the go struct.

    import yaml "gopkg.in/yaml.v2"
    
    err := yaml.UnmarshalStrict(data, destinationStruct)
    

    BurntSushi/toml

    It's not part of the question, but I'd just like to document how to achieve something similar in toml:

    You can find if there were any keys in the toml file that could not be decoded by using the metadata returned by the toml.decode function.

    import "github.com/BurntSushi/toml"
    
    metadata, err := toml.Decode(data, destinationStruct)
    undecodedKeys := metadata.Undecoded()
    

    Note that metadata.Undecoded() also returns keys that have not been decoded because of a Primitive value. You can read more about it here.

    Json

    The default go json library does not support this currently, but there is a proposal ready to be merged. It seems that it will be a part of go 1.10.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据