go · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Six eggs, written in words. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "encoding/json"
import "fmt"
type Item struct {
Name string `json:"name"`
Qty int `json:"qty"`
}
func main() {
var item Item
err := json.Unmarshal([]byte(`{"name": "eggs", "qty": "six"}`), &item)
if err != nil {
fmt.Println("Could not read the order")
return
}
fmt.Println(item.Qty, item.Name)
}
your turn
Your turn. Write some JSON by hand.
Write the JSON for a pet of your own: type its name inside the quotes and its age as a whole number. Then run it to see Unmarshal fill the struct.
output
press run to see what happens
fix it
The café cannot read the order. Fix it!
output
press run to see what happens
- Read the message after Bad order. What does it say about the value you handed over?
- Unmarshal has to fill your box, so it needs the box's address, not a copy of it.
- Change order to &order inside json.Unmarshal on line 10, then run.
nailed it
you can read json from anywhere. :D
json.Unmarshal(data, &value)fills your value from JSON text.- Unknown names are skipped, and missing fields keep their zero value.
- Bad JSON gives an error, so always check it.
new words in your collection
- Unmarshal
- raw string
- parse
This lesson isn’t saved. A free account remembers every lesson you finish.