← 中文资源

简体中文版本

JSON 里的 nil map 与空 map

nil map 编码成 null、空 map 编码成 {};解码 JSON null 得到 nil map(读安全写会 panic),解码 {} 得到已初始化的空 map。

阅读英文原文

实现说明

JSON 里的 nil map 与空 map的核心是函数 main。

使用要点

  • 演示输出是带标签的(nil:、empty:、null -> nil:),每个操作都会留下自己的一行标注。

常见问题

运行「JSON 里的 nil map 与空 map」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 nil:、empty:、null -> nil: 标签标明各步骤。

核心语句

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

代码示例

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))
}