System Design

G15

JSON

encoding/json is the most used package in a Go service, and it is lax by default. Here are its rules from real runs, the strict form for a request body, and encoding/json/v2, which is no longer an experiment in Go 1.27.

Not startedSaved in this browser only.
  1. 1Decode into a typed struct. A number in any is a float64, and a float64 holds 53 bits.
  2. 2Decode is lax: it ignores unknown names, matches any case, and stops after one value.
  3. 3omitempty asks if the value is empty. omitzero asks if it is the zero value.
  4. 4Go 1.27 ships encoding/json/v2, and the old API now runs on it. New code should use v2.
G15
    A

    The trap

    the last digit changes
    decode into a mapgo
    package main
    
    import (
      "encoding/json"
      "fmt"
    )
    
    func main() {
      body := []byte(`{"id": 90071992547409931}`)
    
      var v map[string]any2
      json.Unmarshal(body, &v)
      fmt.Printf("%.0f\n", v["id"])
    
      out, _ := json.Marshal(v)3
      fmt.Println(string(out))
    }
    1. 1Valid JSON, and a valid int64. It is 2 to the power 53, plus 1.
    2. 2With no type to guide it, Decode stores every number as a float64.
    3. 3The damage is permanent: a proxy that decodes and encodes changes the ID.
    decode intorecorded outputstatus
    map[string]any{"id":9007199254740992}Wrong ID
    struct, int64 field{"id":9007199254740993}Exact
    • A float64 has 53 bits of mantissa. Above 2 to the power 53, it cannot hold every integer.
    • No error appears. The value is only a little wrong, so a test with small IDs passes.
    • A JavaScript client has the same limit, because its numbers are float64 too.
    • Snowflake-style IDs are larger than this limit.

    An ID above 2 to the power 53 loses digits in a float64. I decode into int64, and I send IDs as strings to JavaScript clients.

    B

    The model: what any holds

    recorded output of the any-types program
    JSONGo value in any
    numberfloat64
    number, with UseNumberjson.Number
    stringstring
    true, falsebool
    array[]any
    objectmap[string]any
    nullnil
    • Decode into any only for data with an unknown shape.
    • A typed struct costs 3.2 µs. The same bytes into any cost 8.9 µs.
    • Fields that are not in the struct are skipped: decoding one field costs 1.9 µs.

    In any, a number is a float64, an array is []any, and an object is map[string]any. For digits I call UseNumber.

    C

    The model: the packages

    Go 1.27 release notes
    encoding/jsonthe v1 API; supported foreverMarshal, Unmarshal, Decoderyour new codethe v2 API, with its own defaultsUnmarshalRead, MarshalWriteDefaultOptionsV1()options you passencoding/json/v2maps Go values to tokens: tags, methods, optionsencoding/json/jsontextreads and writes tokens; checks syntax, UTF-8 and repeated names
    • encoding/json keeps its behaviour. Only the text of errors may differ.
    • The build setting GOEXPERIMENT=nojsonv2 restores the old engine, for now.
    • jsontext is the level for tokens: a proxy or a formatter can use it alone.

    In Go 1.27 the old API is the v2 engine with v1 options. Behaviour stays, but the error text can change, so I never match on it.

    D

    Struct tags

    the idiom and the trap
    tageffectstatus
    json:"name"The wire name. A rename in Go cannot change the API.Approved
    json:"id,string"A number as a JSON string. Safe for JavaScript.Approved
    json:"at,omitzero"Omits the zero value, or what IsZero reports.Approved
    json:"-"Never in the JSON. Use it for hashes and internal data.Approved
    json:"a,omitempty"Omits false, 0, nil and empty. A real 0 disappears.Strings, slices, maps
    unexported fieldIgnored in both directions. A tag on it has no effect.Export it to encode it
    json:"id" twiceSame-depth fields with one name cancel each other.Not approved

    go vet checks the tag syntax and reports a repeated name.

    Every field in an API type has a tag, because the wire name is a contract and a Go rename must not change it.

    E

    One type, every option

    tested
    tagsgo
    // User shows each tag option once.
    type User struct {
      ID      int64     `json:"id,string"1`
      Name    string    `json:"name"`
      Email   string    `json:"email,omitempty"`
      Age     *int2      `json:"age,omitempty"`
      Tags    []string  `json:"tags"3`
      Created time.Time `json:"created,omitzero"4`
      Hash    string    `json:"-"`
      token   string5
    }
    
    // NewUser sets Tags, so that the field encodes as [] and not null.
    func NewUser(id int64, name, token string) User {
      return User{ID: id, Name: name, Tags: []string{}6, token: token}
    }
    1. 1Encodes "9007199254740993" with quotes. Decoding accepts only the quoted form.
    2. 2nil is absent. A pointer to 0 stays in the output.
    3. 3No omit option: this field is always present.
    4. 4omitempty would print year 1 here. See panel F.
    5. 5Unexported, so JSON never reads or writes it.
    6. 6A nil slice would encode as null.

    An optional number is a pointer, so that absent and 0 stay different. A list starts as an empty slice, so clients get [] and not null.

    F

    omitempty or omitzero

    recorded: each cell is the output of a real Marshal
    value of the fieldv1 omitemptyomitzero, v1 and v2v2 omitempty
    int 0OmittedOmitted{"v":0}
    string ""OmittedOmittedOmitted
    bool falseOmittedOmitted{"v":false}
    nil pointerOmittedOmittedOmitted
    pointer to 0{"v":0}{"v":0}{"v":0}
    nil sliceOmittedOmittedOmitted
    empty sliceOmitted{"v":[]}Omitted
    nil mapOmittedOmittedOmitted
    empty mapOmitted{"v":{}}Omitted
    zero struct{"v":{"X":0}}Omitted{"v":{"X":0}}
    zero time.Time{"v":"0001-01-01T00:00:00Z"}Omitted{"v":"0001-01-01T00:00:00Z"}
    Maybe{} with IsZero{"v":{"Set":false}}Omitted{"v":{"Set":false}}
    • Use omitzero for time.Time, for structs, and for any type with an IsZero method.
    • An empty slice stays under omitzero, because only nil is the zero value. Use that to tell "no list" from "empty list".
    • With both options, the field is omitted if either rule says so.

    omitzero is the rule for structs and time, since Go 1.24. In v2, omitempty looks at the JSON, so a 0 stays.

    G

    Custom marshalers

    tested
    customgo
    // Status is an enum with a text form, so it also works as a map key.
    type Status int
    
    // The order states.
    const (
      StatusOpen Status = iota
      StatusPaid
    )
    
    var statusNames = []string{"open", "paid"}
    
    // MarshalText has a value receiver, so every Status encodes.
    func (s Status) MarshalText()1 ([]byte, error) {
      if s < 0 || int(s) >= len(statusNames) {
        return nil, fmt.Errorf("status %d: unknown", int(s))
      }
      return []byte(statusNames[s]), nil
    }
    
    // UnmarshalText rejects a name that is not in the list.
    func (s *Status) UnmarshalText(2b []byte) error {
      i := slices.Index(statusNames, string(b))
      if i < 0 {
        return fmt.Errorf("status %q: unknown", b)
      }
      *s = Status(i)
      return nil
    }
    
    // Cents encodes as a decimal string, so no float touches money.
    type Cents int64
    
    // MarshalJSON writes 1250 as "12.50".
    func (c Cents) MarshalJSON()3 ([]byte, error) {
      sign := ""
      if c < 0 {
        sign, c = "-", -c
      }
      return fmt.Appendf(nil, `"%s%d.%02d"`, sign, c/100, c%100), nil
    }
    
    // UnmarshalJSON reads "12.50" and rejects other shapes.
    func (c *Cents) UnmarshalJSON(b []byte) error {
      if string(b) == "null"4 {
        return nil
      }
      var s string
      if err := json.Unmarshal(b, &s)5; err != nil {
        return fmt.Errorf("cents: %w", err)
      }
      whole, frac, ok := strings.Cut(s, ".")
      if !ok || len(frac) != 2 {
        return fmt.Errorf("cents: %q needs 2 decimals", s)
      }
      n, err := strconv.ParseInt(whole+frac, 10, 64)
      if err != nil {
        return fmt.Errorf("cents: %w", err)
      }
      *c = Cents(n)
      return nil
    }
    1. 1Text form: JSON quotes it, and map keys use it too. MarshalJSON cannot do map keys in the v1 API.
    2. 2A pointer receiver: the method must change the value.
    3. 3A value receiver, so a value in an interface or a map still encodes this way.
    4. 4The rule for an Unmarshaler: null does nothing.
    5. 5Decode the outer JSON with the package. Do not trim quotes by hand.

    MarshalText gives an enum one form for values and map keys. Marshal methods use value receivers, and Unmarshal methods use pointers.

    H

    Embedded structs

    tested
    auditgo
    // Audit is shared by many documents.
    type Audit struct {
      CreatedBy string    `json:"created_by"`
      Updated   time.Time `json:"updated,omitzero"`
    }
    
    // Doc embeds Audit, so its fields sit at the top level.
    type Doc struct1 {
      Audit
      Title string `json:"title"`
    }
    1. 1Audit has no field name or tag, so its fields sit at the top level of Doc.
    rulestatus
    Embed plain structs to share fieldsApproved
    Name the field to keep it nested: Audit AuditApproved
    Embed time.Time or a type with Marshal methodsThe method replaces the parent
    Embed two types with one field nameBoth fields disappear
    Marshal method with a pointer receiverSkipped on a plain value in v1
    []byte for binary dataBase64 string

    The drill runs each of these. A shallower field wins over a deeper one.

    Embedding flattens the fields into the parent. I check that the embedded type has no Marshal method, because that method takes over the parent.

    I

    Streaming

    measured: an array read two ways
    streamgo
    // SumArray reads a JSON array of orders one element at a time,
    // so memory stays flat for any array length.
    func SumArray(r io.Reader) (int64, error) {
      dec := json.NewDecoder(r)
      if _, err := dec.Token()1; err != nil {
        return 0, fmt.Errorf("open bracket: %w", err)
      }
      var total int64
      for dec.More()2 {
        var o payload.Order3
        if err := dec.Decode(&o); err != nil {
          return 0, fmt.Errorf("order: %w", err)
        }
        total += o.Total
      }
      if _, err := dec.Token(); err != nil {
        return 0, fmt.Errorf("close bracket: %w", err)
      }
      return total, nil
    }
    
    // WriteLines writes one JSON value per line (NDJSON).
    func WriteLines(w io.Writer, orders []payload.Order) error {
      buf := bufio.NewWriter(w)4
      enc := json.NewEncoder(buf)
      for i := range orders {
        if err := enc.Encode(&orders[i])5; err != nil {
          return fmt.Errorf("order %d: %w", i, err)
        }
      }
      if err := buf.Flush()6; err != nil {
        return fmt.Errorf("flush: %w", err)
      }
      return nil
    }
    1. 1Reads the opening bracket, so Decode can start on each element.
    2. 2True until the closing bracket.
    3. 3A fresh value per element. A reused value keeps fields from the last element.
    4. 4An Encoder writes once per value. The buffer joins those writes.
    5. 5Encode adds a newline after each value, so this output is NDJSON.
    6. 6Without this, the last bytes stay in the buffer.
    methodpeak heaptime
    ReadFile and Unmarshal97 MB0.36 s
    Decoder, one element at a time3.1 MB0.45 s

    An array of 100,000 orders, 30 MB on disk, median of 3 runs.

    • Unmarshal needs the whole input in memory, and then the whole result.
    • A Decoder holds one element and its read buffer.
    • Use a stream for exports, imports and any array without a size limit.
    • A Decoder is not a validator: it stops with an error at the first bad element, after the earlier ones have run.

    A Decoder reads one element at a time, so memory stays flat. For a large export I write NDJSON through a bufio.Writer.

    J

    Strict request decoding

    tested
    strictgo
    // ReadStrict accepts exactly one JSON value with known fields.
    func ReadStrict(r io.Reader, v any) error {
      dec := json.NewDecoder(r)
      dec.DisallowUnknownFields()1
      if err := dec.Decode(v); err != nil {
        return fmt.Errorf("%w: %v", ErrInvalid, err)
      }
      if err := dec.Decode(&struct{}{})2; !errors.Is(err, io.EOF)3 {
        return fmt.Errorf("%w: data after the value", ErrInvalid)
      }
      return nil
    }
    1. 1A typo in a name is an error, not a default value.
    2. 2A second Decode must hit the end of the input. Any other result means data follows.
    3. 3Trailing spaces and newlines still pass.

    Wrap the body in MaxBytesReader first (see G16). Decoding is not validation: null and an empty object pass here, so check the values next.

    A strict decoder rejects unknown names and trailing data. Then a client typo returns 400 and does not change the meaning of a request.

    K

    RawMessage: decode later

    tested
    rawgo
    // Event carries a payload whose shape depends on Type.
    type Event struct {
      Type string          `json:"type"`
      Data json.RawMessage1 `json:"data"`
    }
    
    // Paid is the payload of a "paid" event.
    type Paid struct {
      Order string `json:"order"`
      Cents int64  `json:"cents"`
    }
    
    // Refund is the payload of a "refund" event.
    type Refund struct {
      Order  string `json:"order"`
      Reason string `json:"reason"`
    }
    
    // ReadEvent decodes the envelope, then only the payload it needs.
    func ReadEvent(b []byte) (any, error) {
      var e Event
      if err := json.Unmarshal(b, &e); err != nil {
        return nil, fmt.Errorf("envelope: %w", err)
      }
      switch e.Type2 {
      case "paid":
        return decodeAs[Paid](e.Data)
      case "refund":
        return decodeAs[Refund](e.Data)
      }
      return nil, fmt.Errorf("event type %q: unknown", e.Type)
    }
    
    func decodeAs[T any]3(b []byte) (T, error) {
      var v T
      if err := json.Unmarshal(b, &v); err != nil {
        return v, fmt.Errorf("payload: %w", err)
      }
      return v, nil
    }
    1. 1Stores the raw bytes of this field. The syntax is checked; the shape is not.
    2. 2One function per event type, and a clear error for an unknown type.
    3. 3One generic helper avoids a decode block in each case.

    RawMessage keeps the bytes of a field, so I read the envelope first and decode the payload only when I know its type.

    L

    See it: one body, three readers

    recorded: each result is a real call

    body {"by": 2}

    readJSON

    Decoder, as in the build kit

    Accepted, By = 2

    ReadStrict

    v1 API, strict

    Accepted, By = 2

    ReadV2

    v2 API, RejectUnknownMembers

    Accepted, By = 2

    • Each reader decodes into a struct with one field: By int with the tag json:"by".
    • Pick "Typo in a name": the kit accepts it, and By is 0.
    • Pick "null" or "Empty object": all three accept it. The handler must still check that By is set.
    • Read the error text of the v2 column: it names a Go type, so do not send it to a client.
    • Package v2 prints "cannot" or "unable to", chosen once per process, so that no code can depend on the text. This page shows one form.

    A repeated name lets two parsers disagree about one request, so I prefer the v2 rule that rejects it.

    M

    Keep every digit

    tested
    numbersgo
    // DecodeAny keeps every number as its original digits.
    func DecodeAny(b []byte) (any, error) {
      dec := json.NewDecoder(bytes.NewReader(b))
      dec.UseNumber()1
      var v any
      if err := dec.Decode(&v); err != nil {
        return nil, fmt.Errorf("decode: %w", err)
      }
      return v, nil
    }
    
    // Int64At reads one field of a decoded object as an int64.
    func Int64At(v any, key string) (int64, error) {
      obj, ok := v.(map[string]any)
      if !ok {
        return 0, fmt.Errorf("%T is not an object", v)
      }
      n, ok := obj[key].(json.Number)2
      if !ok {
        return 0, fmt.Errorf("%s is not a number", key)
      }
      return n.Int64()3
    }
    1. 1Numbers in any become json.Number, which holds the text.
    2. 2The type is now json.Number, so an assertion to float64 fails.
    3. 3Returns an error for a fraction or for a value out of range.

    When the shape is unknown, UseNumber keeps the original digits, and I convert with Int64 or Float64 at the point of use.

    N

    Nil, empty and absent

    the idiom and the trap
    the client must seeGo fieldtag
    Always a list, maybe [][]T, set to emptyjson:"x"
    A list, or no field[]Tomitempty
    A number, 0 is valid, or no field*intomitempty
    A time, or no fieldtime.Timeomitzero
    A value or null*Tjson:"x"
    the server must readGo fieldstatus
    Present or absent*TApproved
    Absent, null or a valuejson.RawMessageCheck the bytes
    Present, by zero valueT0 looks absent

    For a PATCH, absent means keep. A pointer field shows that, but it cannot tell null from absent, so I decide what null means.

    O

    encoding/json/v2: what changes

    recorded: both APIs ran on each input
    behaviourinputv1 APIv2 APIoption that restores v1
    Field names{"NAME":"a"} into json:"name"{Name:a}{Name:}MatchCaseInsensitiveNames
    Nil slice[]int(nil)null[]FormatNilSliceAsNull
    Nil mapmap[string]int(nil)null{}FormatNilMapAsNull
    omitempty on int 0omit{N: 0}{}{"n":0}use omitzero in both
    Repeated name{"a":1,"a":2}map[a:2]errorjsontext.AllowDuplicateNames
    Invalid UTF-8"a\xff""a�"errorjsontext.AllowInvalidUTF8
    HTML characters"<b>&""\u003cb\u003e\u0026""<b>&"jsontext.EscapeForHTML
    Array length[1,2,3] into [2]int[1 2]errorUnmarshalArrayFromAnyLength
    Byte array[3]byte{1, 2, 3}[1,2,3]"AQID"FormatByteArrayAsArray
    Pointer-receiver methodvalue, not pointer{"R":1}"called"CallMethodsWithLegacySemantics
    time.Duration1500 ms1500000000errorFormatDurationAsNano
    Decode over a slice element[{"b":2}] over [{A:1}][{A:1 B:2}][{A:0 B:2}]MergeWithLegacySemantics
    null into a set intnull into 550MergeWithLegacySemantics
    Struct with no exported fieldstruct{ x int }{}errorReportErrorsWithLegacySemantics
    Map key ordermap with 8 keys, 200 runssorted by keyorder variesDeterministic

    In the v2 column, "error" means the call returned an error. The option names come from the encoding/json package documentation.

    v2 is generally available in Go 1.27. Its defaults are strict, and each difference has an option, so I can move one rule at a time.

    P

    The v2 API

    tested
    v2go
    // ReadV2 is ReadStrict in the v2 API. It reads to EOF, so
    // trailing data, unknown names and repeated names all fail.
    func ReadV2(r io.Reader, v any) error {
      err := jsonv2.UnmarshalRead(r, v,1
        jsonv2.RejectUnknownMembers(true)2,
      )
      if err != nil {
        return fmt.Errorf("%w: %v", ErrInvalid, err)
      }
      return nil
    }
    
    // Order keeps its ID as a string on the wire.
    type Order struct {
      ID    int64     `json:"id,string"`
      Tags  []string  `json:"tags"`
      Taken time.Time `json:"taken,omitzero"`
    }
    
    // WriteV2 streams to w with no intermediate slice.
    func WriteV2(w io.Writer, o Order) error {
      if err := jsonv2.MarshalWrite(w, o)3; err != nil {
        return fmt.Errorf("encode: %w", err)
      }
      return nil
    }
    1. 1Takes a Reader and options, with no Decoder object.
    2. 2The v2 form of DisallowUnknownFields.
    3. 3Writes to w directly, for a handler that writes JSON.

    UnmarshalRead reads to the end of the input, so the trailing-data check is built in. One option turns on unknown-name errors.

    Q

    Move to v2?

    the package documentation, and measured
    situationstatus
    New codeUse v2
    Existing code that worksKeep v1; it stays supported
    Migrating a servicejsonv2.Marshal(v, jsonv1.DefaultOptionsV1())
    Clients expect null for empty listsFormatNilSliceAsNull
    time.Duration in an API typePick a form: v2 has no default
    Depending on error textIt changes per process in v2
    Depending on map key order in v2Use Deterministic

    Engine change, same v1 API, same order: Unmarshal 5.1 µs before, 3.2 µs now. Marshal 1.2 µs before, 1.6 µs now.

    New code uses v2. In an existing service I start with DefaultOptionsV1 and turn on one strict rule at a time.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.22Encoding writes \b and \f, not \u0008 and \u000c.Output changed for those two characters.
    1.24The omitzero tag option, with IsZero support. UnmarshalTypeError.Field includes embedded structs.time.Time can now be omitted with a tag.
    1.25encoding/json/v2 and jsontext as an experiment, behind GOEXPERIMENT=jsonv2.You could test the new engine. It was off by default.
    1.27encoding/json/v2 and jsontext are available with no setting. encoding/json runs on the v2 engine. GOEXPERIMENT=nojsonv2 opts out, and the notes expect that to go in a future release.Behaviour stays. Error text can change. Unmarshal is faster.
    1.27Changes since the experiment: the format and unknown tag options, DiscardUnknownMembers and SkipFunc are gone. The inline tag option is now embed. jsontext number accessors return errors.Code written for the experiment needs edits.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildYou type readJSON from the K1 kit.One Decode into a struct, wrapped as ErrInvalid. It is enough to pass, so move on.
    buildThe kit declares var body struct{ By int } with no tag.It works because v1 matches the name By in any case. In v2, add json:"by".
    buildA field is required.Use a pointer, or check the zero value. Decode does not know about required fields.
    buildThe prompt returns a list.Start with make, so an empty result is [] and not null.
    talk"What would you harden in readJSON?"A size limit, DisallowUnknownFields, a trailing-data check, and a fixed client message for the error.
    talk"How do you add a field to an API?"Readers must ignore unknown names, so strict decoding fits a public request body, not a response you read.
    talk"Why not float64 for money?"Decimal fractions do not fit binary floats. Use integer cents, or a decimal string on the wire.
    talk"Is JSON the bottleneck?"One order is 317 bytes and costs about 1.6 µs. Measure first, and compare with the database call.

    In the build I use the kit's readJSON. In the talk I name what it accepts by accident, and how I would close each gap.

    T

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type Stock struct {
        Item  string `json:"item"`
        Count int    `json:"count,omitempty"`
        Sold  *int   `json:"sold,omitempty"`
      }
      
      func main() {
        zero := 0
        out, _ := json.Marshal(Stock{Item: "pen", Count: 0, Sold: &zero})
        fmt.Println(string(out))
      }
    2. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
        "time"
      )
      
      type A struct {
        At time.Time `json:"at,omitempty"`
      }
      
      type B struct {
        At time.Time `json:"at,omitzero"`
      }
      
      func main() {
        a, _ := json.Marshal(A{})
        b, _ := json.Marshal(B{})
        fmt.Println(string(a))
        fmt.Println(string(b))
      }
    3. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      func main() {
        var nilSlice []int
        empty := []int{}
        var nilMap map[string]int
      
        a, _ := json.Marshal(nilSlice)
        b, _ := json.Marshal(empty)
        c, _ := json.Marshal(nilMap)
        fmt.Println(string(a), string(b), string(c))
      }
    4. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type Req struct {
        Name string `json:"name"`
      }
      
      func main() {
        var a, b Req
        json.Unmarshal([]byte(`{"NAME": "upper"}`), &a)
        json.Unmarshal([]byte(`{"name": "lower", "nAmE": "last"}`), &b)
        fmt.Println(a.Name, b.Name)
      }
    5. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
        "strings"
      )
      
      type Req struct {
        Limit int `json:"limit"`
      }
      
      func main() {
        body := `{"limt": 10}`
      
        var a Req
        err := json.Unmarshal([]byte(body), &a)
        fmt.Println(a.Limit, err)
      
        var b Req
        dec := json.NewDecoder(strings.NewReader(body))
        dec.DisallowUnknownFields()
        err = dec.Decode(&b)
        fmt.Println(b.Limit, err != nil)
      }
    6. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
        "strings"
      )
      
      type Req struct {
        N int `json:"n"`
      }
      
      func main() {
        body := `{"n": 1} {"n": 2} garbage`
      
        var a Req
        err := json.NewDecoder(strings.NewReader(body)).Decode(&a)
        fmt.Println(a.N, err)
      
        var b Req
        err = json.Unmarshal([]byte(body), &b)
        fmt.Println(b.N, err != nil)
      }
    7. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
        "time"
      )
      
      type Event struct {
        time.Time
        Name string `json:"name"`
      }
      
      func main() {
        e := Event{
          Time: time.Date(2026, 3, 7, 9, 0, 0, 0, time.UTC),
          Name: "deploy",
        }
        out, _ := json.Marshal(e)
        fmt.Println(string(out))
      }
    8. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type A struct{ ID int }
      
      type B struct{ ID int }
      
      type Both struct {
        A
        B
        Title string `json:"title"`
      }
      
      type Outer struct {
        A
        ID string
      }
      
      func main() {
        x, _ := json.Marshal(Both{A{1}, B{2}, "t"})
        y, _ := json.Marshal(Outer{A{1}, "top"})
        fmt.Println(string(x))
        fmt.Println(string(y))
      }
    9. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type Color struct{ R int }
      
      func (c *Color) MarshalJSON() ([]byte, error) {
        return []byte(`"custom"`), nil
      }
      
      func main() {
        c := Color{R: 1}
        a, _ := json.Marshal(c)
        b, _ := json.Marshal(&c)
        fmt.Println(string(a), string(b))
      }
    10. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type Blob struct {
        Data []byte `json:"data"`
        Raw  []int8 `json:"raw"`
      }
      
      func main() {
        out, _ := json.Marshal(Blob{Data: []byte("hi"), Raw: []int8{104, 105}})
        fmt.Println(string(out))
      }
    11. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type Config struct {
        Host string         `json:"host"`
        Port int            `json:"port"`
        Tags map[string]int `json:"tags"`
      }
      
      func main() {
        c := Config{Host: "a", Port: 80, Tags: map[string]int{"x": 1}}
        json.Unmarshal([]byte(`{"port": 443, "tags": {"y": 2}}`), &c)
        fmt.Println(c.Host, c.Port, c.Tags)
      }
    12. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      func main() {
        var v any
        json.Unmarshal([]byte(`{"n": 1, "ok": true, "l": [1], "o": {}, "s": "x", "z": null}`), &v)
        m := v.(map[string]any)
        for _, k := range []string{"n", "ok", "l", "o", "s", "z"} {
          fmt.Printf("%s=%T ", k, m[k])
        }
        fmt.Println()
        _, isInt := m["n"].(int)
        fmt.Println(isInt)
      }
    U

    Numbers to say

    measured on one order of 317 bytes
    Marshal
    1.6 µs and 3 allocations; v2 API 1.6 µs.
    Unmarshal
    3.2 µs and 9 allocations; v2 API 2.7 µs.
    into any
    8.9 µs and 77 allocations.
    by hand
    487 ns with strconv and no reflection, 3.2 times faster than Marshal.
    2^53
    9,007,199,254,740,992. Up to here, a float64 holds every integer exactly.
    new engine
    Unmarshal runs 1.6 times faster than the old one on this order.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.