×

go · level 2 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

fills your struct from JSON text.

Reading JSON is the other way round. err := json.Unmarshal(data, &order) reads the JSON in data and fills in order. It needs the address, &order, because it changes your box, and data must be a byte slice, so write []byte(text).

JSON is full of double quotes, so write it as a : text between backtick marks instead of double quotes, like a struct tag. Unmarshal matches JSON names to your struct tags. Unknown names are skipped, and missing fields keep their zero value.

To is to read text and work out its structure. If the text is not proper JSON, or a value has the wrong type, Unmarshal hands back an error. Data from outside your program can be anything, so always check.

package main
import "encoding/json"
import "fmt"
type Order struct {
	Snack string `json:"snack"`
	Qty   int    `json:"qty"`
	Note  string `json:"note"`
}
func main() {
	text := `{"snack": "crisps", "qty": 2, "table": 7}`
	var order Order
	err := json.Unmarshal([]byte(text), &order)
	if err != nil {
		fmt.Println("Bad order:", err)
		return
	}
	fmt.Printf("%d x %s, note: %q\n", order.Qty, order.Snack, order.Note)
}

A JSON value in the wrong form, such as 2.5 for an int field, also gives an error.