Go: Decode independent JSON records into fresh structs
Reusing a struct for independent JSON records can carry a value from one record into the next. An omitted field keeps its previous value, and JSON null does not reset an integer field. Start each independent decode with a fresh target.
Set up
Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as go-json-fresh-record-target.go:
package main
import (
"encoding/json"
"fmt"
)
type Record struct {
Name string `json:"name"`
Count int `json:"count"`
}
func main() {
inputs := []string{
`{"name":"tea","count":5}`,
`{"name":"coffee"}`,
`{"name":"water","count":null}`,
}
var reused Record
for _, input := range inputs {
if err := json.Unmarshal([]byte(input), &reused); err != nil {
panic(err)
}
var fresh Record
if err := json.Unmarshal([]byte(input), &fresh); err != nil {
panic(err)
}
fmt.Printf("name=%s reused=%d fresh=%d\n", fresh.Name, reused.Count, fresh.Count)
}
}Run:
go run go-json-fresh-record-target.goObserved output:
name=tea reused=5 fresh=5
name=coffee reused=5 fresh=0
name=water reused=5 fresh=0Read the result
The reused target keeps the first count when the next record omits it. It also keeps that count when the third record explicitly supplies null. Each fresh target begins with zero-valued fields, so neither later record inherits the earlier count.
Declaring the target inside the loop gives each input its own zero-valued record. If decoding fails, reject that target: a type error can leave some fields populated. A successful decode still needs application validation before the record is used.
Apply it carefully
This approach suits independent records whose omitted fields should take their zero values. For a patch operation, preserving fields may be intentional, but that requires an explicit update contract. Fresh decoding still cannot distinguish an absent integer, null and an explicit zero here. Track field presence separately if the application needs that distinction.
The example uses the standard encoding/json package with ordinary exported fields. Custom unmarshaling methods can define different behavior. Validate required fields and business rules after decoding, and publish the new record to shared state only after all checks pass.
See the Unmarshal reference.
Clean up
Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.
rm -- go-json-fresh-record-target.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.