Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle optional JSON field in HTTP request body

Tags:

json

go

I have a struct like this:

type MyStruct struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
} 

Then I have some value (could be default, which means I do not need to update this value) to feed in as HTTP request data. I noticed the generated JSON body will always contains all three fields (name, age and email), even if I don't need to update all of them. Like this:

{
  "name":"Kevin",
  "age":10,
  "email":""
}

Is there a way to Marshal so that the JSON body contains not all fields with the same struct? Example:

{
  "name":"kevin"
}
like image 262
Kevin Avatar asked Dec 02 '15 21:12

Kevin


1 Answers

You want to use the omitempty option

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

If you want Age to be optional as well you have to use a pointer, since the zero value of an int isn't really "empty"

type MyStruct struct {
    Name  string `json:"name,omitempty"`
    Age   *int   `json:"age,omitempty"`
    Email string `json:"email,omitempty"`
}
like image 152
JimB Avatar answered Nov 01 '22 21:11

JimB