[SOLVED] Json unmarshal struct to map is ignoring zero values of struct

Issue

This Content is from Stack Overflow. Question asked by Samaha Hcndcl

I am trying to convert a struct to map using following method

func ConvertStructToMap(in interface{}) map[string]interface{} {
    fmt.Println(in)
    var inInterface map[string]interface{}
    inrec, _ := json.Marshal(in)
    json.Unmarshal(inrec, &inInterface)
    return inInterface

}

The problem is when I am trying to convert a struct

type Data struct{
 Thing string `json:"thing,omitempty"`
 Age uint8 `json:"age,omitempty"`

}

With this data

c:=Data{
  Thing :"i",
  Age:0,
}

it just gives me the following output map[things:i] instead it should give the output
map[things:i,age:0]

And when I don’t supply age

like below

 c:=Data{
      Thing :"i",
      
    }

Then it should give this output map[things:i] .I am running an update query and the user may or may not supply the fields ,any way to solve it .I have looked over the internet but couldn’t get my head on place



Solution

omitempty ignore when convert from struct to json

type Response struct {
 Age int `json:"age,omitempty"`
 Name string `json:"name,omitempty"`
}

resp:=Response {
  Name: "john",
}

 data,_:=json.Marshal(&resp)
fmt.Println(string(data)) => {"name": "john"}

In you case, you convert from json to struct, if attribute not present, it will be fill with default value of data type, in this case is 0 with uint8


This Question was asked in StackOverflow by Samaha Hcndcl and Answered by taismile It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?