errchkjson

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 17 Imported by: 17 modules, 13 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

errchkjson

Test Status Go Report Card License

Checks types passed to the json encoding functions. Reports unsupported types and reports occurrences where the check for the returned error can be omitted.

Consider this http.Handler:

func JSONHelloWorld(w http.ResponseWriter, r *http.Request) {
	response := struct {
		Message string
		Code    int
	}{
		Message: "Hello World",
		Code:    200,
	}

	body, err := json.Marshal(response)
	if err != nil {
		panic(err) // unreachable, because json encoding of a struct with just a string and an int will never return an error.
	}

	w.Write(body)
}

Because the panic is not possible to happen, one might refactor the code like this:

func JSONHelloWorld(w http.ResponseWriter, r *http.Request) {
	response := struct {
		Message string
		Code    int
	}{
		Message: "Hello World",
		Code:    200,
	}

	body, _ := json.Marshal(response)

	w.Write(body)
}

This is ok, as long as the struct is not altered in such a way, that could potentially lead to json.Marshal returning an error.

errchkjson allows you to lint your code such that the above error returned from json.Marshal can be omitted while still staying safe, because as soon as an unsafe type is added to the response type, the linter will warn you.

Installation

Download errchkjson from the releases or get the latest version from source with:

go install github.com/breml/errchkjson/cmd/errchkjson@latest

Usage

Shell

Check everything:

errchkjson ./...

errchkjson also recognizes the following command-line options:

The -omit-safe flag disables checking for safe returns of errors from json.Marshal

Types

Safe

The following types are safe to use with json encoding functions, that is, the encoding to JSON can not fail:

Safe basic types:

  • bool
  • int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr
  • string
  • Pointer type of the above listed basic types

Composed types (struct, map, slice, array) are safe, if the type of the value is safe. For maps, the key needs to be either an integer type or a string.

For structs, only the fields, which are encoded, are relevant. These are the exported fields, including the exported fields promoted from embedded structs (even if the type of the embedded struct is unexported). An embedded struct with a JSON name is a field on its own, even if its type is unexported, its fields are not promoted. If multiple fields use the same JSON object name, the conflict is resolved using the Go embedding rules (the less nested field wins, otherwise a field with an explicit JSON name wins, otherwise all of these fields are ignored). Some fields are handled differently depending on the Go version (e.g. because of a JSON name containing quotes or the inline or embed option). Such a field is relevant, if at least one supported Go version encodes it, see Go 1.27 and later.

Unsafe

The following types are unsafe to use with json encoding functions, that is, the encoding to JSON can fail (return an error):

Unsafe basic types:

  • float32, float64
  • interface{}
  • Pointer type of the above listed basic types

Any composed types (struct, map, slice, array) containing an unsafe basic type.

If a type implements the json.Marshaler or encoding.TextMarshaler interface (e.g. json.Number). If the interface is implemented with a pointer receiver (e.g. func (*T) MarshalJSON() ([]byte, error)), the type is only unsafe, if the value can be addressed, because encoding/json does not call the method otherwise. Values behind pointers (e.g. json.Marshal(&v)) and elements of slices can be addressed, map keys and map values can not. Struct fields and elements of arrays can be addressed, if the struct or array can be.

Recursive types (e.g. type Node struct{ Next *Node } or type Tree map[string]Tree), because encoding fails for cyclic values and for values with a nesting depth larger than 10000 (see Nesting depth). A struct embedding itself without a JSON name (e.g. type T struct{ *T }) is not recursive, because an embedded struct is only visited once. With a JSON name (e.g. type T struct{ *T `json:"t"` }), it is recursive.

Forbidden

Forbidden basic types:

  • complex64, complex128
  • chan
  • func
  • unsafe.Pointer

Arrays (of length greater than 0), slices, maps, pointers and structs containing a forbidden type, as well as maps with a key type, which is neither an integer type, nor a string, nor implements encoding.TextMarshaler (e.g. bool, float64, struct or pointers). Nil and empty values of such types (e.g. a nil []chan int, a nil *chan int or a zero value in a struct field with the omitzero option) are encoded without error. Nevertheless, these types are forbidden, because such a value is expected to contain a value of the forbidden type at some point, which then fails at runtime. Arrays of length 0 are encoded without considering the element type and are therefore not forbidden.

For structs, the check stops at the first unsafe or forbidden field. A field, which is only unsafe because some Go versions do not encode its forbidden type, does not stop the check for forbidden fields. Recursive types, marshaler interfaces implemented with a pointer receiver, embedded structs of unexported types with a JSON name and fields promoted from embedded structs of unexported types are an exception (unless the embedded struct has an unsafe format option, see Go 1.27 and later). They are only considered, if the checked type is safe otherwise or if it is only unsafe, because some Go versions do not encode a forbidden type. In the latter case, only forbidden types are reported.

Go 1.27 and later

As of Go 1.27, encoding/json is implemented on top of encoding/json/v2, because the experiment GOEXPERIMENT=jsonv2 is enabled by default (it can still be disabled with GOEXPERIMENT=nojsonv2). The behavior of encoding/json therefore depends on the Go version (and GOEXPERIMENT) used to build a program. errchkjson can not know this and therefore considers a type unsafe, if encoding it can fail with any supported Go version. A type is only forbidden, if encoding it fails with all of them: if a field of a forbidden type is not encoded by some Go versions (e.g. because it is hidden by an other field), the struct is unsafe instead. In addition to the above rules, the following is considered unsafe:

  • Types implementing the MarshalJSONTo(*jsontext.Encoder) error method (json.MarshalerTo of encoding/json/v2) or the encoding.TextAppender interface.
  • Struct fields with the format option in the json struct tag (e.g. json:"when,format:RFC3339"). A format option without a valid value (e.g. format: or format:123) and a format option on an embedded struct without JSON name are ignored by encoding/json and are therefore not reported.

encoding/json/v2

errchkjson also checks the functions Marshal, MarshalWrite and MarshalEncode of encoding/json/v2 (available as of Go 1.27 or with GOEXPERIMENT=jsonv2 for Go 1.26). The rules for safe, unsafe and forbidden types are the same as above, with the following differences:

  • string (including named string types and string map keys) is unsafe, because encoding/json/v2 returns an error for strings containing invalid UTF-8.
  • time.Duration is forbidden, because it has no default representation in encoding/json/v2. As for other forbidden types, it is forbidden behind pointers, in slices and maps and in struct fields with the omitzero option. It is unsafe as map key and in struct fields with the format option (supported by Go 1.26).
  • Types, which implement one of the marshaler interfaces with a pointer receiver (e.g. func (*T) MarshalJSON() ([]byte, error)), are unsafe, even if they are passed by value, because encoding/json/v2 always calls these methods.
  • Map keys of float types (e.g. map[float64]string) are unsafe, because NaN and infinite values fail.
  • Map keys of byte array types (e.g. map[[16]byte]string) are safe, because they are encoded as base64 encoded strings.
  • A forbidden type is reported, even if the struct also contains unsafe fields (e.g. string), independent of the order of the fields.
  • The fields, which are encoded, are determined for each supported version of encoding/json/v2. Fields promoted from an embedded pointer are checked like other fields, although they are not encoded, if the pointer is nil.

The definition of a struct (e.g. its json struct tags) is checked, when a value of the struct type is encoded. Struct definitions, which are rejected by all supported versions of encoding/json/v2 (Go 1.26 with GOEXPERIMENT=jsonv2 and Go 1.27 or newer), are forbidden. As for other forbidden types, they are forbidden behind pointers, in slices and maps or in struct fields with the omitzero option. The following struct definitions are forbidden:

  • Structs with two or more direct fields using the same JSON object name. Conflicts with fields promoted from embedded structs are not an error (see above).
  • Structs with fields, but without any exported field and without any json struct tag.
  • Struct fields with a JSON object name containing a backslash or quote characters (e.g. json:"a'b") or invalid UTF-8.
  • Unexported struct fields with a json struct tag other than json:"-".
  • Embedded fields of non-struct types (e.g. type MyInt int or an interface), if they are not explicitly given a JSON name (e.g. json:"name") or if their type is unexported.
  • Struct fields with malformed options in the json struct tag, e.g. a trailing comma (json:"name,"), misspelled options (e.g. omitEmpty), duplicate options, case with a value other than ignore or strict, format without a valid value or followed by another option, or single-quoted strings, which are not terminated (e.g. json:"name,'x"). Unknown options are ignored by encoding/json/v2 and are therefore not reported, unless they appear more than once.
  • Embedded structs without a JSON name with options (other than embed) or of a type, which implements one of the marshaler or unmarshaler interfaces (e.g. func (*T) UnmarshalJSON([]byte) error).
  • Embedded structs of unexported types with a JSON name (e.g. inner `json:"in"` ), if their type implements one of the marshaler or unmarshaler interfaces, or the IsZero() bool method in combination with the omitzero option, because these methods can not be called.

Struct definitions, which are only rejected by some versions of encoding/json/v2, are unsafe. If a struct contains several such definitions, which together are rejected by all versions, the struct is forbidden. The following struct definitions are unsafe:

  • Struct fields with the format option (rejected as of Go 1.27). If Go 1.26 does not support the value of the option for the type of the field (e.g. format:RFC3339 for an int), the field is rejected by all versions and therefore forbidden.
  • Struct fields with the string option, if the type of the field is not numeric (rejected as of Go 1.27). Types with marshal methods are not affected, because their methods are called without considering the option (except for time.Time and interfaces).
  • Struct fields with a single-quoted JSON object name (e.g. json:"'name'", rejected as of Go 1.27) or with single-quoted options (e.g. json:"name,'x y'").
  • Struct fields with the JSON object name - and options (e.g. json:"-,omitempty", rejected by Go 1.26).
  • Struct fields with misspelled embed options (rejected as of Go 1.27) or misspelled inline or unknown options (rejected by Go 1.26).
  • Fields with the embed option (or the options inline or unknown, the predecessors of embed in Go 1.26), if they have a JSON name or options other than embed, if their type is not a struct, a map with a string key or jsontext.Value, if their type (or the map key type) implements one of the marshaler or unmarshaler interfaces, or if a struct has more than one such field of a map type or jsontext.Value.
  • Conflicts of the JSON object name of a field with the embed, inline or unknown option with other fields, because these fields are regular fields for one of the versions (e.g. a field F T `json:",embed"` conflicts with a field using the JSON name F for Go 1.26). If such a field (or a field with a single-quoted JSON object name) is not encoded by this version, because of a name conflict with a field promoted from another struct, a forbidden type of the field is only unsafe.
  • Forbidden types of fields, which are only encoded by some versions. The fields of a struct with the inline option are promoted by Go 1.26, the fields of a struct with the embed option as of Go 1.27, the encoded fields are therefore determined for each version (e.g. the field C of In in struct{ C int; In struct{ C chan int } `json:",inline"` } is only encoded as of Go 1.27).

Further differences:

  • Constant arguments, which are a string with valid UTF-8 or a float (e.g. json.Marshal("hello") or json.Marshal(1.5)), are safe, because constants are always finite. This does not apply to types implementing one of the marshaler interfaces.

  • If options are passed to the function (e.g. json.WithMarshalers), the encoding of any type can be changed and the call is therefore always considered unsafe. For MarshalEncode, the options of the jsontext.Encoder apply as well, types are therefore never considered forbidden.

Because MarshalWrite and MarshalEncode may return errors unrelated to the encoded type (e.g. from the io.Writer), their returned error is never reported as safe to omit, similar to (*encoding/json.Encoder).Encode.

Nesting depth

Encoding fails for values with a nesting depth larger than 10000:

  • With Go 1.26 (and with GOEXPERIMENT=nojsonv2 as of Go 1.27), this only applies to encoding/json.MarshalIndent (see the scanner of encoding/json) and to (*encoding/json.Encoder).Encode after a call of SetIndent.
  • As of Go 1.27 (and with GOEXPERIMENT=jsonv2 for Go 1.26), this applies to all functions of encoding/json.

In addition, encoding fails for cyclic values (with all Go versions). Recursive types, which allow such values (e.g. type Node struct{ Next *Node }), are therefore reported as unsafe for encoding/json and encoding/json/v2 (see #94).

As an accepted (pathological) edge case, a type, which exceeds this nesting depth without being recursive, is not detected. The types would have to be nested more than 10000 levels deep in the source code.

Bugs found during development

During the development of errcheckjson, the following issues in package encoding/json of the Go standard library have been found and PR have been merged:

Documentation

Overview

Package errchkjson defines an Analyzer that finds places, where it is safe to omit checking the error returned from json.Marshal.

Index

Constants

This section is empty.

Variables

View Source
var Version = "errchkjson version dev"

Functions

func NewAnalyzer

func NewAnalyzer() *analysis.Analyzer

NewAnalyzer returns a new errchkjson analyzer.

Types

This section is empty.

Directories

Path Synopsis
cmd
errchkjson command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL