go · level 2 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
is how programs share data, and writes it.
Programs all over the world swap data as JSON text. It looks like this: {"name":"Rex","age":3}. Curly brackets hold named values, square brackets hold lists, and strings sit in double quotes. Web servers, apps and files all speak it.
The encoding/json toolbox does the work. data, err := json.Marshal(rex) turns a struct, slice or map into JSON and hands it back as a byte slice, so print it with string(data). Only fields starting with a capital letter are included.
A renames a field in the JSON. Write it between backtick marks after the field's type, as json:"name". Adding ,omitempty, as in json:"toy,omitempty", leaves the field out whenever it holds its zero value.
package main
import "encoding/json"
import "fmt"
type Pet struct {
Name string `json:"name"`
Age int `json:"age"`
Tricks []string `json:"tricks"`
Toy string `json:"toy,omitempty"`
secret string
}
func main() {
rex := Pet{Name: "Rex", Age: 3, Tricks: []string{"sit", "roll"}, secret: "hates baths"}
data, err := json.Marshal(rex)
if err != nil {
fmt.Println("Could not make JSON:", err)
return
}
fmt.Println(string(data))
} json.MarshalIndent(rex, "", " ") gives the same JSON spread over several lines, which is easier to read.
guess first
No struct tags this time. 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 Snack struct {
Name string
price int
}
func main() {
data, _ := json.Marshal(Snack{Name: "crisps", price: 2})
fmt.Println(string(data))
}
your turn
Your turn. Share a film review.
Choose the names the JSON should use for the two fields, in small letters. Then add a film you like and a rating from 1 to 5.
output
press run to see what happens
fix it
The player's name keeps its capital letter. Fix it!
output
press run to see what happens
- Score comes out as score, but Name keeps its capital. Compare the two struct tags closely.
- The name inside a struct tag must sit in double quotes, as it does in json:"score".
- Change json:name to json:"name" on line 5, then run.
nailed it
your data can travel as json. :D
- JSON is text that almost every program can read.
json.Marshalturns a Go value into JSON, as a byte slice.- Struct tags rename fields, and lowercase fields are skipped.
new words in your collection
- JSON
- Marshal
- struct tag
This lesson isn’t saved. A free account remembers every lesson you finish.