Nil Versus Empty Maps In JSON

Marshal a nil map as JSON null and an empty map as {}, and remember decoding null hands back a nil map while {} yields an initialized empty one.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Report struct {
	// nil map 与空 map 编码结果不同:null 与 {}
	Tags map[string]string `json:"tags"`
}

func main() {
	var nilTags map[string]string
	emptyTags := map[string]string{}

	a, _ := json.Marshal(Report{Tags: nilTags})
	fmt.Println("nil:", string(a))
	b, _ := json.Marshal(Report{Tags: emptyTags})
	fmt.Println("empty:", string(b))

	// 解码方向:JSON null -> nil map(读安全写 panic);{} -> 非 nil 空 map
	var fromNull Report
	_ = json.Unmarshal([]byte(`{"tags": null}`), &fromNull)
	var fromEmpty Report
	_ = json.Unmarshal([]byte(`{"tags": {}}`), &fromEmpty)

	fmt.Println("null -> nil:", fromNull.Tags == nil)
	fmt.Println("{} -> initialized:", fromEmpty.Tags != nil, "len", len(fromEmpty.Tags))
}

How it works

Count the function main as the entire surface area of Nil Versus Empty Maps In JSON.

Using it

Running the file prints labeled results such as nil:, empty:, null -> nil: — each operation’s effect is visible in the output.

Key statements

_ = json.Unmarshal([]byte(`{"tags": null}`), &fromNull)

Interactive Tools for This Topic

FAQ

What does Nil Versus Empty Maps In JSON print when run?
Running the file directly is enough — expect labeled output lines such as `nil:`, `empty:`, `null -> nil:`.