JSON in and out in Go
Marshal and Unmarshal, with tags deciding the wire names.
type Tour struct {
Slug string `json:"slug"`
Steps int `json:"steps"`
Sets []string `json:"sets,omitempty"`
}
func roundTrip() (string, int, error) {
original := Tour{Slug: "traits", Steps: 19, Sets: []string{"Traits"}}
data, err := json.MarshalIndent(original, "", " ")
if err != nil {
return "", 0, fmt.Errorf("marshal: %w", err)
}
var back Tour
if err := json.Unmarshal(data, &back); err != nil {
return "", 0, fmt.Errorf("unmarshal: %w", err)
}
return back.Slug, len(data), nil
}
How it works
- Only exported fields are encoded.
- Unmarshal into a pointer, and check the error.
MarshalIndentis the readable form.
Keywords and builtins used here
errorfuncifintlenreturnstringstructtypevar
The run, in numbers
- Lines
- 19
- Characters to type
- 495
- Tokens
- 128
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.
Step 2 of 3 in Encoding, step 2 of 26 in Standard library & project layout.