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.
Code
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
JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.