encoding/json

Tags decide field names. An unknown field is silently skipped by default, and a parse error must not be hidden.

encoding/json looks at exported fields. The name in JSON is taken from the json tag. Without a tag the field name is used as it is.

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

json.Unmarshal fills the struct and returns an error if the bytes are not JSON. Unknown fields are ignored by default. That is convenient for evolving a protocol and dangerous if a typo in a tag silently leaves a field at zero. A test on a concrete JSON catches it. Decoder.DisallowUnknownFields turns on a strict mode when the contract is narrow.

Zero values and omitempty are connected. A field with json:",omitempty" is skipped if it is zero. A pointer distinguishes "they did not send it" from "they sent zero" when that is truly needed. Do not make every field a pointer "just in case": the code fills up with nil checks.

Marshal of a nil slice gives null, of an empty slice []. An API response usually wants [], so the slice must not be nil. A map behaves similarly.

Do not parse JSON into map[string]any if the shape is known. A struct documents the contract and catches the type of id at compile time after parsing... no, the type is checked during parsing, and that is already better than pulling any out by hand. map[string]any is left for a truly free object.

The error from Unmarshal is returned to the caller. Substituting an empty struct and going on means accepting garbage as a user.

Practice

  1. Where the JSON name comes from

    The field is called Name, the tag is json:"name". Which key appears in the JSON?

    • Name
    • name
    • Name, and the tag affects only XML
    • The field disappears. Tags forbid export
  2. A name from JSON

    Write UserName(data string) string. Parse the JSON object and return the field name. If the JSON is broken or the field is missing, return an empty string.

  3. An empty list in the response

    The client expects a JSON array. Which slice do you return when there are no elements?

    • A nil slice
    • An empty non-nil slice
    • A map with no keys
    • There is no difference. Both become []