質問

I want to traverse the nested JSON struct and get each key and value from the interface{}

http://play.golang.org/p/B-B3pejGJW

So I want from the following struct

    {
        "tg": {
            "A": {
                "E": 100,
                "H": 14
            },
            "B": {
                "D": 1
            },
            "C": {
                "D": 1,
                "E": 1
            },
            "D": {
                "F": 1,
                "G": 1,
                "H": 1
            },
            "E": {
                "G": 1
            }
        }
    }

I was able to get the following

a := js.Get("tg").Get("D").Get("F")
fmt.Println(*a) // {1}

but having trouble with type assert this to integer.

     invalid type assertion: (*a).(int)

How would would traverse this whole struct and get each integer mapped from the characters?

Thanks!

役に立ちましたか?

解決

Your value will be marshalled into a float64. Plus you are not accessing a.data but a instead which is a struct which is causing the error.

fmt.Printf("%#v\n", a)              // &main.JSON{data:1}
fmt.Println(reflect.TypeOf(a.data)) // float64
x := int(a.data.(float64))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top