encoding/json

encoding/json maps a struct to an object by field name, with a tag to rename a field or leave it out when empty. The package is part of the standard library, so a Go program can speak JSON with no dependency, which is why it is the format of the API lessons in Part 8. The struct is the schema: the field types are the validation, and a field that does not fit is an error with a message.

Marshal and tags

Marshal returns bytes and string(bytes) is what a program prints or sends. A tag renames a field, omitempty drops it when it holds the zero value, and an unexported field is never encoded. MarshalIndent writes the same object with line breaks and a prefix per level, for a file or a log rather than a wire.

package main import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Email string `json:"email,omitempty"` Age int `json:"age"` Admin bool `json:"admin"` } func main() { u := User{Name: "ada", Age: 36} data, err := json.Marshal(u) fmt.Println(string(data)) fmt.Println("error:", err) u.Email = "ada@example.com" data, err = json.MarshalIndent(u, "", " ") fmt.Println(string(data)) fmt.Println("error:", err) }

go build -o app main.go && ./app

{"name":"ada","age":36,"admin":false}
error: <nil>
{
  "name": "ada",
  "email": "ada@example.com",
  "age": 36,
  "admin": false
}
error: <nil>

The first object has no email because the field was empty and the tag said omitempty, and it keeps admin: false because a bool has no omitempty. Fields come out in the order of the struct, which is stable but not what the JSON specification promises; a client that needs a particular order gets it from the struct, not from the encoder.

Unmarshal

Unmarshal reads an object into a pointer to a struct and matches the keys through the tags. A key the struct does not have is ignored, which is what makes a client tolerant of a server that added a field. A key that is there but has the wrong type is an error, and the sections below take the two cases apart.

package main import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age"` } func main() { var u User err := json.Unmarshal([]byte(`{"name":"grace","age":45,"extra":1}`), &u) fmt.Printf("%+v\n", u) fmt.Println("error:", err) }

go build -o app main.go && ./app

{Name:grace Age:45}
error: <nil>

The extra key was ignored and the two known fields filled in. A server that must reject an unknown field calls DisallowUnknownFields on a decoder, which the next lesson does; a client that talks to a changing API keeps the default and ignores what it does not know.

Numbers and precision

A JSON number without a type is a float64 in an any, and a float64 holds fifty-three bits of mantissa. The number below is one more than that, and it comes back changed. A decoder in UseNumber mode keeps the digits in a json.Number, and Int64 reads them into an exact integer.

package main import ( "encoding/json" "fmt" "strings" ) func main() { dec := json.NewDecoder(strings.NewReader(`{"id": 9007199254740993}`)) dec.UseNumber() var m map[string]any err := dec.Decode(&m) fmt.Println("error:", err) n := m["id"].(json.Number) fmt.Println("number:", n) i, err := n.Int64() fmt.Println("int64:", i, err) var f float64 json.Unmarshal([]byte(`9007199254740993`), &f) fmt.Println("float64:", f) }

go build -o app main.go && ./app

error: <nil>
number: 9007199254740993
int64: 9007199254740993 <nil>
float64: 9.007199254740992e+15

The float ended in 992 instead of 993, which is the rounding a fifty-three-bit mantissa forces. An identifier that must stay exact is a string in the JSON, not a number; the next best is a struct field of type int64, which the decoder fills exactly because it knows the target type.

A field of the wrong type

The decoder reports the field path and both types, and it does so while reading the object: the fields before the bad one are already filled, and the ones after it are not, so a failed Unmarshal leaves a partial value. A caller that needs all or nothing decodes into a fresh variable and only assigns it on success.

package main import ( "encoding/json" "fmt" ) type User struct { Name string `json:"name"` Age int `json:"age"` } func main() { var u User err := json.Unmarshal([]byte(`{"age":"old"}`), &u) fmt.Println("error:", err) }

go build -o app main.go && ./app

error: json: cannot unmarshal string into Go struct field User.age of type int

The message names the Go type, the field and the JSON type, which is enough to fix the client or to map the error to a 400. A syntax error reads differently: invalid character 'o' looking for beginning of value comes with the offset, and the strict mode above adds the line for a stream.

The rules of encoding/json

An exported field is encoded, an unexported one is not, and a tag with a dash skips a field. A map[string]T becomes an object with sorted keys, a slice becomes an array, and a nil slice becomes null unless the field is omitted. A struct field with omitempty is dropped for zero values of numbers, strings, booleans, nil pointers and empty slices and maps, but not for a struct, which is why a nested struct needs a pointer to be omittable.

Two limits matter for an API. The encoder escapes HTML characters such as < by default, which is right for a page and surprising for a JSON client; Encoder.SetEscapeHTML(false) turns it off. And encoding/json is a reflection-based encoder, fast enough for a request per millisecond and slower than a generated encoder for a million messages; the benchmark part of the capstone measures the difference.

Exercises

  1. Add a Password string `json:"-"` field and marshal the struct. Is the value in the output, and what does the dash do on Unmarshal?
  2. Marshal a nil slice field and then an empty one. What does each produce, and what does omitempty change?
  3. Unmarshal an object with a number into a field of type string and read the error. Which type does the message name first?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does json.Marshal return?

    Answer

    A slice of bytes and an error

    string(data) is what a program prints or sends.

  2. What does a json tag rename?

    Answer

    The key of the field in the object

    The tag is the wire name.

  3. What does omitempty drop?

    Answer

    A field that holds its zero value

    Structs are not omitted without a pointer.

  4. What happens to an unknown key on Unmarshal?

    Answer

    It is ignored

    DisallowUnknownFields is the strict variant.

  5. What type is a JSON number in an any?

    Answer

    float64

    UseNumber keeps the digits instead.

  6. Why did 9007199254740993 become 992 as a float64?

    Answer

    The mantissa has only fifty-three bits

    An exact id belongs in a string or an int64 field.

  7. What does the error of a wrong field type name?

    Answer

    The Go type, the field and the JSON type

    That is enough for a 400.

  8. What does an unexported field do in JSON?

    Answer

    It is never encoded or decoded

    Only exported fields take part.

  9. What does Encoder.SetEscapeHTML(false) change?

    Answer

    It stops escaping < > and &

    The default is safe for HTML, surprising for an API.

  10. What does a nil slice field encode as?

    Answer

    null

    An empty slice encodes as [].

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev