Go json.Unmarshal
json.Unmarshal decodes JSON into a Go value. Using a pointer field preserves the distinction between a numeric zero and a missing or null value.
A simple example
json.Unmarshal
- Start with JSON text {"n":2}
- Do this Decode and read field n
- Result Number 2
Syntax
err := json.Unmarshal(data, &item)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Distinguish a zero quantity from an absent one
A dataset includes a missing or optional measurement alongside actual numerical values. Make the missing-value policy explicit so a valid zero is not discarded or silently replaced.
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Item struct{ Qty *int }
for _, record := range []string{"{\"Qty\":0}", "{}"} {
var item Item
if err := json.Unmarshal([]byte(record), &item); err != nil {
panic(err)
}
if item.Qty == nil {
fmt.Println("unspecified")
} else {
fmt.Println(*item.Qty)
}
}
}
0 unspecified
Decode each record into a fresh struct. When reusing a populated struct, a missing JSON member can leave its previous value in place.
Go documentation for json.Unmarshal
Read a locker report
A locker controller sends the number of free doors as JSON. Decode the JSON record before reading its count field. Which numeric count reaches the desk?
Record an empty tray
A sorter sends an explicit count of zero for an empty tray. Decode the JSON record before reading its count field. Which numeric count reaches the desk?