Distinguish nil, empty, omitted and null
Distinguish nil, empty, omitted and null
JSON null, an empty array [] and an absent property can represent different states. With Go 1.23.2 encoding/json, a nil non-byte slice marshals as null; an initialized empty non-byte slice marshals as []. An omitempty slice field omits either when length is zero.
package main
import ( "encoding/json" "fmt")
func check(e error) { if e != nil { panic(e) }}
type Payload struct { Items []string `json:"items"` Optional []string `json:"optional,omitempty"`}
func main() { for _, v := range [][]string{nil, {}} { b, e := json.Marshal(Payload{Items: v, Optional: v}) check(e) fmt.Println(string(b)) }}Choose the wire representation intentionally. The special []byte representation is different: non-nil bytes encode as a base64 string. For maps, a nil map encodes as null and an empty initialized map as {}.
Expected output:
{"items":null}{"items":[]}Detect presence with RawMessage
package main
import ( "encoding/json" "fmt")
func check(e error) { if e != nil { panic(e) }}
func main() { for _, s := range []string{`{}`, `{"items":null}`, `{"items":[]}`} { var p struct { Items json.RawMessage `json:"items"` } check(json.Unmarshal([]byte(s), &p)) fmt.Printf("%t %q\n", p.Items == nil, string(p.Items)) }}RawMessage holds the raw JSON bytes for later decoding. Decode into a fresh struct each time. For an ordinary pointer field, both absent and explicit null can leave a fresh pointer nil; RawMessage lets you distinguish those states. Validate the raw value before using it.
Expected output:
true ""false "null"false "[]"Try it locally
Marshal a nil map[string]int and an initialized empty map[string]int, one per line.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 03: Distinguish nil, empty, omitted and null
Check the lesson objective before moving on.
What does an initialized empty []int marshal to without omitempty?
How can a fresh struct distinguish absent from explicit null?