7.5 json-tag

本篇学习 Go json tag 的常见选项(字段重命名、忽略字段、omitempty)并能正确序列化结构体。

字数 520 字

json tag

概念说明

json tag 是结构体字段上 json:"..." 形式的标签。
它用于控制结构体转 JSON 时的字段名和行为。

语法/规则

  1. 不写 json tag 时,JSON 字段名默认使用结构体字段名。
  2. 小写字段(未导出)不会被 encoding/json 编码。
  3. json:"-" 表示该字段在 JSON 中忽略。
  4. json:",omitempty" 表示字段是零值时省略输出。
  5. 多个选项写在同一个 tag 里,例如 json:"age,omitempty"

忽略字段示例(json:"-"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Name     string `json:"name"`
	Age      int    `json:"age"`
	Password string `json:"-"`
}

func main() {
	student := Student{
		Name:     "阿斌",
		Age:      21,
		Password: "123456",
	}

	byteData, _ := json.Marshal(student)
	fmt.Println(string(byteData))
}

输出结果:

1
{"name":"阿斌","age":21}

空值省略示例(omitempty

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Name string `json:"name"`
	Age  int    `json:"age,omitempty"`
}

func main() {
	student := Student{
		Name: "阿斌",
		Age:  0,
	}

	byteData, _ := json.Marshal(student)
	fmt.Println(string(byteData))
}

输出结果:

1
{"name":"阿斌"}

常见错误

  1. 字段名小写(未导出)却期望参与 JSON 编解码,结果字段被忽略。
  2. json:"-"omitempty 混淆:前者是永远忽略,后者是零值时忽略。
  3. 误以为 omitempty 会过滤空字符串之外的所有“无效值”,实际按类型零值规则判断。
使用 Hugo 构建
主题 StackJimmy 设计 由 Hobin 魔改
载入天数...载入时分秒...
发表了 0 篇文章 · 发表了 46 篇笔记 · 总计 2 万 5 千字(其中笔记 25104 字)