I'm trying to parse a yaml file while keeping the order (due to foreign key issues) of tables being processed.
fixtures.yaml
table1:
-id: 1
field1: "some value"
field2: "some value"
table2:
-id: 1
field1: "some value"
field2: "some value"
...some more data...
main.go
yamlContent, err := ioutil.ReadFile("fixtures.yaml")
yamlOutput := yaml.MapSlice{}
err := yaml.Unmarshal(yamlContent, &yamlOutput)
if err != nil {
log.Fatal(err)
}
for _, tableData := range yamlOutput {
//Table Name
fmt.Println(tableData.Key)
//Table Data
fmt.Println(tableData.Value)
// Error here
for _, row := range tableData.Value {
fmt.Println(row)
}
}
The value of tableData.Value looks something like this:
[[{id 1} {field1 some value} {field2 some value} {field3 some value} {field4 some value} {field5 some value}]]
The problem is I cannot range through tableData.Value
. Whenever I do, I get the error:
cannot range over tableData.Value (type interface {})
But whenever I use reflect.TypeOf(tableData.Value)
, I get []interface {}
What should I do to be able to loop through each row and then through each key value pair? I'm pretty new in Go so I'm not really sure what to do next.
CodePudding user response:
If you have a value that has static type interface{}
whose dynamic type is []interface{}
then you have to type-assert it to the dynamic type to be able to range over the slice.
if v, ok := tableData.Value.([]interface{}); ok {
for _, row := range v {
fmt.Println(row)
}
}