package main
import (
"fmt"
"encoding/json"
"log"
)
type X struct {
A int `json:"a,omitempty"`
C int `json:"c,omitempty"`
}
type Y struct {
B int
}
func main() {
type M interface {
}
m := map[string]M{ "k1": X{A:33}, "k2": Y{B:2} }
data := `{"c": 22}`
cc := m["k1"]
fmt.Printf("%#v", cc)
fmt.Println("-------------- ")
err := json.Unmarshal([]byte(data), &cc)
fmt.Printf("%#v", cc)
log.Println(m)
fmt.Println(err)
//fmt.Println("Hello, playground")
}
Hi, @Mukul_Dilwaria, your code is unmarshaling cc; your Printf shows that the new value in cc becomes a map[string]interface{} from the unmarshaled JSON, {"c": 22}. Can you clarify what you were expecting?
The type of m is map[string]M which is what I’ll call “equivalent” to type map[string]interface{}.
The type of cc here is M which is equivalent to interface{} which is an interface type. The Unmarshal function’s documentation here says:
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null
Because you’re unmarshaling into a interface type and the JSON value you’re unmarshaling ({"c": 22}) is a JSON object, the resulting type is map[string]interface{} as the documentation states.