Library contents

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

  1. Start with JSON text {"n":2}
  2. Do this Decode and read field n
  3. Result Number 2
Decoding turns the text representation into an object or record with a numeric field.

Syntax

Go 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.

First output line0
main.go
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)
		}
	}
}
Output
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

Advertisements

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?

Given{"count":4}
Worked result4

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?

Given{"count":0}
Worked result0