有没有办法确保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?

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.