Im a newbie in golang. I am trying to validate a yaml structure
prof:
res:
- ed:
app:
conf:
For that i have read the yaml file using ioutil, then converted it to map string interface. I tried 1) looping over map interface 2) converting it to json string using marshal and then looping but couldn't achieve it.
Any help will be appreciated. Thanks
yfile, err1 := ioutil.ReadFile("C:/Users/212764682/user.yaml")
data := make(map[string]interface{})
err := yaml.Unmarshal(yfile, &data)
Tried iterating like this
for key, value := range data {
if key == "prof" {
for key2, value2 := range value.(map[string]interface{}) {
if key2 == "res" {
for key3, value3 := range value2.(map[string]interface{}) {
if key3 == "ed" {
for key4, value4 := range value3.(map[string]interface{}) {
if key4 == "app" {
for key5 := range value4.(map[string]interface{}) {
if key5 == "conf" {
fmt.Println("valid format")
}
}
}
}
}
}
}
}
}
}
CodePudding user response:
You don't have to range over all the keys in a map to find out if it contains a key. See the following example:
if dict2, ok := dict1["foo"]; ok {
if dict3, ok := dict2["bar"]; ok {
if dict4, ok := dict3["goo"]; ok {
// and so on
} else {
// key was not found, error
}
} else {
// key was not found, error
}
} else {
// key was not found, error
}
CodePudding user response:
Use structs. There are online services to autogenerate the struct from your yaml file. There are many and they are easy to find. Generate a struct and then you can use something like this code:
package main
import (
"fmt"
"log"
"github.com/go-yaml/yaml"
"io/ioutil"
)
type User struct {
Prof struct {
Res []struct {
Ed struct {
App struct {
Conf struct {
Field1 int `yaml:"field1"`
Field2 int `yaml:"field2"`
} `yaml:"conf"`
} `yaml:"app"`
} `yaml:"ed"`
} `yaml:"res"`
} `yaml:"prof"`
}
func NewUser(name string) (*User, error) {
user := new(User)
file, err := ioutil.ReadFile(name)
if err != nil {
return nil, fmt.Errorf("read: %w", err)
}
if err := yaml.Unmarshal(file, user); err != nil {
return nil, fmt.Errorf("unmarshal: %w", err)
}
return user, nil
}
func main() {
user, err := NewUser("user.yaml")
if err != nil {
log.Fatalf("user: %s", err)
}
fmt.Printf("% v\n", *user)
}