I wanto print a complicate dataset like bellowing
package main
import (
    "fmt"
    // "reflect"
)
func main() {
    var initData []interface{}
    initData[0] = map[string]interface{}{
        "name": "k1",
        "type": "line",
        "data": []int{1, 2, 3, 4},
    }
    initData[1] = map[string]interface{}{
        "name": "k2",
        "type": "circle",
        "data": []int{11, 12, 13, 14},
    }
    for _, data := range initData {
        for k, v := range data {
            fmt.Println(k)
            for _, sv := range v {
                fmt.Println("  " + sv)
            }
        }
    }
}
but get an error
./maps-in-maps.go:56: cannot range over data (type interface {})
any help? to try to concert the interface typed dataset to interable like arry or slice
You must type assert each interface{} level first, in this case, use a type assertion at map[string]interface{} level since we know a definite type, and a type switch to check anticipated types for each nested value in the next level.
initData := []interface{}{
        map[string]interface{}{
            "name": "k1",
            "type": "line",
            "data": []int{1, 2, 3, 4},
        },
        map[string]interface{}{
            "name": "k2",
            "type": "circle",
            "data": []int{11, 12, 13, 14},
        },
    }
    for _, data := range initData {
        for _, v := range data.(map[string]interface{}) {
            switch t := v.(type) {
            case string, []int:
                fmt.Println(t)
            default:
                fmt.Println("wrong type")           
            }
        }
    }
}
Run playground here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With