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

标签 go yaml

为了测试,我经常看到go代码读取字节 slice ,使用yaml解析成结构,例如这里:

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

我只是因为没有导出我的字段名称而被咬了一口,导致我在我的测试用例中迭代了一个空列表,因此假设所有测试都通过了(事后看来,这应该是一个危险信号 :))。 yaml 解码会悄悄忽略其他错误,例如键拼写错误以及与结构字段不完全匹配。

有没有办法确保字节 slice 中的所有数据实际上都被解析到 yaml.Unmarshal 返回的结构中?如果不是,其他人如何处理这种情况?

最佳答案

go-yaml/yaml

对于寻找此问题解决方案的任何人,yaml.v2 库都有一个 UnmarshalStrict如果 yaml 文档中的键在 go 结构中没有对应的字段,则返回错误的方法。

import yaml "gopkg.in/yaml.v2"

err := yaml.UnmarshalStrict(data, destinationStruct)

BurntSushi/toml

这不是问题的一部分,但我只想记录如何在 toml 中实现类似的东西:

通过toml.decode函数返回的元数据,可以发现toml文件中是否有无法解码的key。

import "github.com/BurntSushi/toml"

metadata, err := toml.Decode(data, destinationStruct)
undecodedKeys := metadata.Undecoded()

请注意,metadata.Undecoded() 还会返回因 Primitive 值而未解码的键。你可以read more about it here .

Json

默认的 go json 库目前不支持这个,但是有一个 proposal ready to be merged .看起来它将成为 go 1.10 的一部分。

关于go - 有没有办法确保解析 yaml 字符串中的所有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882558/

相关文章:

在 for 每个循环中使用 go 例程时,由 func 文字捕获的 go vet 范围变量

go - 该方法不应该明确地与接口(interface)的签名签约吗?

Golang Google Drive Oauth2 不返回刷新 token

boolean - Ansible 到底如何解析 boolean 变量?

github - 在导入之前我必须有文件是没有意义的

go - Twirp 不适用于原型(prototype)

python - 使用 python ruamel-yaml 保持 YAML 文件的偏移缩进

python - 使用 Python 删除 YAML 文件中的 block

从 Doctrine 中的新 YAML 迁移数据库

yaml - 向测试厨房添加属性