JSON Skips Unexported And Dash Fields

encoding/json silently drops unexported struct fields, and the json:"-" tag excludes exported ones from both marshal and unmarshal roundtrips.

GoSecurity Boundaries

Code

snippet
package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	password string // 未导出 (unexported) 字段:encoding/json 永远不会触碰
	APIKey   string `json:"-"` // dash 标签:显式要求序列化时跳过
	Age      int    `json:"age,omitempty"`
}

func main() {
	u := User{
		Name:     "Ada",
		Email:    "[email protected]",
		password: "hunter2",
		APIKey:   "sk-live-123",
		Age:      36,
	}

	out, err := json.Marshal(u)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(out))

	// 反序列化同样只认导出字段:password 与 APIKey 保持零值
	var back User
	if err := json.Unmarshal(out, &back); err != nil {
		panic(err)
	}
	fmt.Println("password empty:", back.password == "")
	fmt.Println("api key empty:", back.APIKey == "")
}

How the snippet works

The snippet is organized around the function main.

Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Watch out for

  • No third-party packages are used — the runtime ships every API called here.
  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

Entry signature: func main()

The file’s steps are announced right in the output: password empty:, api key empty:.

Core lines

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does JSON Skips Unexported And Dash Fields print when run?
The script runs standalone; its 2 labeled outputs include `password empty:`, `api key empty:`.