Nil Versus Empty Slices In JSON
Nil slices marshal to null, empty slices to []; both append and iterate identically, and omitempty drops either because a length-zero slice counts as empty.
Code
package main
import (
"encoding/json"
"fmt"
)
func main() {
// nil 切片:var 声明的零值,没有底层数组
var nilTags []string
emptyTags := []string{}
nilJSON, _ := json.Marshal(nilTags)
emptyJSON, _ := json.Marshal(emptyTags)
fmt.Printf("nil -> %s\n", nilJSON) // null
fmt.Printf("empty -> %s\n", emptyJSON)
// 运行时行为一致:len 相同、append 与 range 都安全
fmt.Println("same len:", len(nilTags) == len(emptyTags))
nilTags = append(nilTags, "go")
fmt.Println("nil usable after append:", nilTags)
// omitempty 按长度判空:encoding/json 把 empty value 定义为
// "any array, slice, map, or string of length zero"——nil 与 []
// 都会被省略,不做 nil 与空切片的区分。
// tags 带 omitempty 从输出里消失;roles 不带,空切片照样输出 []
resp := struct {
Name string `json:"name"`
Tags []string `json:"tags,omitempty"`
Roles []string `json:"roles"`
}{Name: "svc", Tags: emptyTags, Roles: []string{}}
out, _ := json.Marshal(resp)
fmt.Println(string(out)) // {"name":"svc","roles":[]}
}What runs when
Nil Versus Empty Slices In JSON is built around the function main.
Applying it
Running the file prints labeled results such as nil ->, empty ->, same len: — each operation’s effect is visible in the output.
Statements that matter
nilTags = append(nilTags, "go")
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does Nil Versus Empty Slices In JSON print when run?
- No setup needed: run the file and look for labeled lines like `nil ->`, `empty ->`, `same len:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.