1

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

  • 2
    It is ignoring fields with zero value because _you asked_ it with the `,omitempty` option. If you want all fields, remove the `,omitempty` options from the tags. – icza Sep 17 '22 at 21:35
  • Actually I am sending a json from frontend which gets converted to struct by `ctx.BodyParser() of gofiber `then I am converting the struct to map ,if i remove omitempty ,Bodyparser just gives me whole struct with empty fields :( – Samaha Hcndcl Sep 17 '22 at 21:39
  • 1
    You can directly convert the request body to map using `ctx.BodyParser()` `var payload map[string]interface{} if err := c.BodyParser(&payload); err != nil { }`. As BodyParser takes interface as argument – Shubham Dixit Sep 17 '22 at 21:50
  • 1
    There is no difference between "set to zero" or "left to zero" fields, see [Default struct values](https://stackoverflow.com/questions/40970422/default-struct-values/40970490#40970490). `Data{Thing: "i", Age: 0}` is equivalent to `Data{Thing: "i"}`. Use pointers if you need this. – icza Sep 17 '22 at 21:51

1 Answers1

0

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

taismile
  • 101
  • 7