typestar

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

  1. Only exported fields are encoded.
  2. Unmarshal into a pointer, and check the error.
  3. MarshalIndent is the readable form.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →

JSON in and out in other languages