How to declare a map with values with different of struct and unmarshall them

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")
}

Why i am not able to unmarshal it ?
My output

main.X{A:33, C:0}--------------   
map[string]interface {}{"c":22}2009/11/10 23:00:00 map[k1:{33 0} k2:{2}]
<nil>
1 Like

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?

2 Likes

yes that is the issue only … how could cc becomes an map[string]interface {}{"c":22}

2 Likes

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.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.