JSON Pointer Fields Track Presence

Decode optional fields into pointer types so missing or null JSON reads as nil instead of the zero value, with omitempty dropping nil fields on marshal.

GoData Integrity

Code

gosnippet
43 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Profile struct {
	Name string  `json:"name"`
	Bio  *string `json:"bio"`           // 缺失或显式 null 都解成 nil
	Age  *int    `json:"age,omitempty"` // nil 在 Marshal 时整个字段省略
}

func describe(p Profile) string {
	bio := "unset"
	if p.Bio != nil {
		bio = fmt.Sprintf("%q", *p.Bio)
	}
	if p.Age != nil {
		return fmt.Sprintf("name=%s bio=%s age=%d", p.Name, bio, *p.Age)
	}
	return fmt.Sprintf("name=%s bio=%s age=unset", p.Name, bio)
}

func main() {
	payloads := []string{
		`{"name":"ada","bio":"builder","age":30}`,
		`{"name":"ada","bio":""}`,
		`{"name":"ada"}`,
	}
	for _, raw := range payloads {
		var p Profile
		if err := json.Unmarshal([]byte(raw), &p); err != nil {
			fmt.Println("bad payload:", err)
			continue
		}
		fmt.Println(describe(p))
	}

	// 未加 omitempty 的 nil 指针输出 null;加了 omitempty 的直接省略
	out, _ := json.Marshal(Profile{Name: "ada"})
	fmt.Println(string(out))
}

How it works

All the doing happens inside the functions describe and main — everything else is wiring.

The one repetition in this snippet is the loop for _, raw := range payloads. Nothing falls through silently — 1 checkpoint test err != nil on the way through.

Putting it to use

The callable that matters: func describe(p Profile) string

Running the file prints labeled results such as bad payload: — each operation’s effect is visible in the output.

Launch the file; main takes over and steps through describe.

The core lines, annotated

return fmt.Sprintf("name=%s bio=%s age=%d", p.Name, bio, *p.Age)
return fmt.Sprintf("name=%s bio=%s age=unset", p.Name, bio)
for _, raw := range payloads {
var p Profile
if err := json.Unmarshal([]byte(raw), &p); err != nil {
fmt.Println("bad payload:", err)
continue
}
fmt.Println(describe(p))
}

Interactive Tools for This Topic

FAQ

What does JSON Pointer Fields Track Presence print when run?
No setup needed: run the file and look for labeled lines like `bad payload:` in the output.