Standard library / encoding/json

JSON nil, empty and null

Nil slices and maps encode as null, non-nil empty slices as [] and non-nil empty maps as {}. Missing fields and explicit null are distinct at the wire level; ordinary scalar fields do not reliably preserve that distinction. Expected stdout: '[null,[],null,{}]\n'.

Formal Syntax & Structure

go syntaxgo
nil slice/map → null; empty non-nil slice/map → [] / {}

Working Example

Example Snippetgo
package main
import (  "encoding/json"  "fmt")
func must(e error) {  if e != nil {    panic(e)  }}
func main() {  b, e := json.Marshal([]any{[]int(nil), []int{}, map[string]int(nil), map[string]int{}})  must(e)  fmt.Println(string(b))}
Go Reference