Skip to content

Instantly share code, notes, and snippets.

@liggitt
Created December 4, 2015 22:41
Show Gist options
  • Save liggitt/51924670d6b78cd5ee72 to your computer and use it in GitHub Desktop.
Save liggitt/51924670d6b78cd5ee72 to your computer and use it in GitHub Desktop.
omitempty behavior with zeros, nulls, and numbers
package main
import (
"encoding/json"
"fmt"
)
func main() {
zero := 0
one := 0
empty, _ := json.Marshal(A{})
fmt.Println(string(empty))
zeros, _ := json.Marshal(A{Int: zero, IntPointer: &zero, IntOmit: zero, IntPointerOmit: &zero})
fmt.Println(string(zeros))
ones, _ := json.Marshal(A{Int: one, IntPointer: &one, IntOmit: one, IntPointerOmit: &one})
fmt.Println(string(ones))
}
type A struct {
Int int `json:"int"`
IntPointer *int `json:"intPointer"`
IntOmit int `json:"intOmit,omitempty"`
IntPointerOmit *int `json:"intPointerOmit,omitempty"`
}
@liggitt
Copy link
Author

liggitt commented Dec 4, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment