Skip to content

Instantly share code, notes, and snippets.

@hallyn
Created February 15, 2021 03:23
Show Gist options
  • Save hallyn/6ab48db33b5c53f2de52f0d507a54f37 to your computer and use it in GitHub Desktop.
Save hallyn/6ab48db33b5c53f2de52f0d507a54f37 to your computer and use it in GitHub Desktop.
Extensible nested yaml fields in golang
```
package main
import (
"fmt"
"os"
"gopkg.in/yaml.v2"
)
var indata string = `
version: 1
field1: "value1"
nest:
nestF1: v1
nestF2: |
Four score and seven years ago,
our fathers...
`
type yaml1 struct {
Version string `yaml:"version"`
Field1 string `yaml:"field1"`
Nested interface{} `yaml:"nest"`
}
type wrappedYaml struct {
Field1 string `yaml:"nestF1"`
Field2 string `yaml:"nestF2"`
}
func main() {
c := []byte(indata)
fmt.Printf("c is %v\n", c)
struct1 := &yaml1{}
err := yaml.Unmarshal(c, struct1)
if err != nil {
fmt.Printf("unmarshall error %v\n", err)
os.Exit(1)
}
fmt.Printf("struct1 is is %v\n", struct1)
struct2 := struct1.Nested.(map[interface{}]interface{})
fmt.Printf("wrapped field1 is %v\n", struct2)
fmt.Printf("struct2.Field1 is %s\n", struct2["nestF1"])
fmt.Printf("struct2.Field2 is %s\n", struct2["nestF2"])
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment