Assigning null to JSON fields instead of empty strings

In json package documentation :

Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON object.

So you can store a pointer to a string which will be encoded as a string if not nil and will be encoded as “null” if nil

type student struct {
  FirstName  *string `json:"first_name"`
  MiddleName *string `json:"middle_name"`
  LastName   *string `json:"last_name"`
}

Leave a Comment