Search code examples
gotype-assertion

Type assert a nested interface


I json.Unmarshal JSON into an interface{}. I can't type assert it. http://play.golang.org/p/NAe8voYnb8.

package main

import (
    "encoding/json"
    "log"
)

func main() {
    b := []byte(`{"key1":[
                          {"apple":"A", "banana":"B", "id": "C"},
                          {"cupcake": "C", "pinto":"D"}
                         ]
                  }`)

    var data interface{}
    _ = json.Unmarshal(b, &data)

    log.Println(data)
    // map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]

    ndata, ok := data.(map[string][]map[string]string)
    log.Println(ok, ndata)
    // false map[]

    key_data, ok := ndata["key1"].([]map[string]string)
    log.Println(ok, key_data)
    // false []
}

Anyone know what's up?


Solution

  • For example,

    package main
    
    import (
        "encoding/json"
        "log"
    )
    
    func somefunc(data interface{}) {
        log.Printf("%T\n", data)
        // Prints: map[string]interface {}
        log.Println(data)
        // Correctly prints: map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]
    
        ndata, _ := data.(map[string]interface{})
        log.Println(ndata)
        // Should print: map[key1:[map[apple:A banana:B id:C] map[cupcake:C pinto:D]]]
    
        key_data, _ := ndata["key1"]
        log.Println(key_data)
        // Should print: [map[apple:A banana:B id:C] map[cupcake:C pinto:D]]]
    }
    
    func main() {
        b := []byte(`{"key1":[{"apple":"A", "banana":"B", "id": "C"},{"cupcake": "C", "pinto":"D"}]}`)
        var m interface{}
        _ = json.Unmarshal(b, &m)
        somefunc(m)
    }
    

    Output:

    2012/10/18 18:21:43 map[string]interface {}
    2012/10/18 18:21:43 map[key1:[map[apple:A id:C banana:B] map[cupcake:C pinto:D]]]
    2012/10/18 18:21:43 map[key1:[map[banana:B apple:A id:C] map[pinto:D cupcake:C]]]
    2012/10/18 18:21:43 [map[banana:B apple:A id:C] map[pinto:D cupcake:C]]