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
- Backtick tags rename fields for JSON.
omitemptydrops zero values from output.MarshalandUnmarshalconvert both ways.
Keywords and builtins used here
boolbyteerrorfuncintreturnstringstructtypevar
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.
Step 1 of 3 in Encoding, step 1 of 26 in Standard library & project layout.