How to marshal objects to `yaml.Node`?
septs opened this issue · comments
We known that json.RawMessage is an unmarshaled (unencoded) json byte array, but yaml.Node
is NOT.
How to marshal objects (structs) to yaml.Node instead of yaml encoded byte array?
Pseudo Code:
type Example struct {
Type string `yaml:"type"`
Options yaml.Node `yaml:"options"`
}
example := new(Example)
yaml.Unmarshal(input, example) // OK
if example.Type == "foo" {
var foo FooExample
example.Options.Decode(&foo) // OK
}
// but
example := new(Example)
example.Type = "foo"
example.Options = ? // how to foo marshal to yaml.Node?
yaml.Marshal(example)
We use
type RawNode struct{ *yaml.Node }
func (n *RawNode) UnmarshalYAML(value *yaml.Node) error {
n.Node = value
return nil
}
For this unmarshalling, and instead of Options yaml.Node
, you'd use Options RawNode
var foo FooExample
yaml.Marshal(foo) // returns byte array, but i need `yaml.Node`
You'd still use the Decode
similar to what you had before, just unwrap from the RawNode struct:
example.Options.Node.Decode(&foo)