typestar

JSON encoding in Go

Struct tags map Go fields to JSON keys.

type Repo struct {
    Name  string `json:"name"`
    Stars int    `json:"stargazers_count"`
    Fork  bool   `json:"fork,omitempty"`
}

func encode(repos []Repo) ([]byte, error) {
    return json.MarshalIndent(repos, "", "  ")
}

func decode(data []byte) ([]Repo, error) {
    var repos []Repo
    err := json.Unmarshal(data, &repos)
    return repos, err
}

How it works

  1. Backtick tags rename fields for JSON.
  2. omitempty drops zero values from output.
  3. Marshal and Unmarshal convert both ways.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
330
Tokens
79
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 1 of 3 in Encoding, step 1 of 26 in Standard library & project layout.

Next →