×

go · level 2 · unit 6 · lesson 3

  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

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.