Json unmarshal struct to map is ignoring zero values of struct

Viewed 40

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

Edit - I am sending json from frontend which gets converted to struct with go fiber Body parser

if err := c.BodyParser(&payload); err != nil {
        
    }

Now If I send following payload from frontend

{
  thing:"ii"
}

the bodyParser converts it into

Data{
          Thing :"ii",
          Age :0
          
        }

that's why I have used omitempty such that bodyParser can ignore the field which are not present

1 Answers

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

Related