README
¶
errchkjson
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:
boolint,int8,int16,int32,int64,uint,uint8,uint16,uint32,uint64,uintptrstring- 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,float64interface{}- 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,complex128chanfuncunsafe.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) errormethod (json.MarshalerToofencoding/json/v2) or theencoding.TextAppenderinterface. - Struct fields with the
formatoption in thejsonstruct tag (e.g.json:"when,format:RFC3339"). Aformatoption without a valid value (e.g.format:orformat:123) and aformatoption on an embedded struct without JSON name are ignored byencoding/jsonand 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, becauseencoding/json/v2returns an error for strings containing invalid UTF-8.time.Durationis forbidden, because it has no default representation inencoding/json/v2. As for other forbidden types, it is forbidden behind pointers, in slices and maps and in struct fields with theomitzerooption. It is unsafe as map key and in struct fields with theformatoption (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, becauseencoding/json/v2always calls these methods. - Map keys of float types (e.g.
map[float64]string) are unsafe, becauseNaNand 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
jsonstruct 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
jsonstruct tag other thanjson:"-". - Embedded fields of non-struct types (e.g.
type MyInt intor 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
jsonstruct tag, e.g. a trailing comma (json:"name,"), misspelled options (e.g.omitEmpty), duplicate options,casewith a value other thanignoreorstrict,formatwithout 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 byencoding/json/v2and 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 theIsZero() boolmethod in combination with theomitzerooption, 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
formatoption (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:RFC3339for anint), the field is rejected by all versions and therefore forbidden. - Struct fields with the
stringoption, 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 fortime.Timeand 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
embedoptions (rejected as of Go 1.27) or misspelledinlineorunknownoptions (rejected by Go 1.26). - Fields with the
embedoption (or the optionsinlineorunknown, the predecessors ofembedin Go 1.26), if they have a JSON name or options other thanembed, if their type is not a struct, a map with a string key orjsontext.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 orjsontext.Value. - Conflicts of the JSON object name of a field with the
embed,inlineorunknownoption with other fields, because these fields are regular fields for one of the versions (e.g. a fieldF T `json:",embed"`conflicts with a field using the JSON nameFfor 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
inlineoption are promoted by Go 1.26, the fields of a struct with theembedoption as of Go 1.27, the encoded fields are therefore determined for each version (e.g. the fieldCofIninstruct{ 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")orjson.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. ForMarshalEncode, the options of thejsontext.Encoderapply 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=nojsonv2as of Go 1.27), this only applies toencoding/json.MarshalIndent(see the scanner ofencoding/json) and to(*encoding/json.Encoder).Encodeafter a call ofSetIndent. - As of Go 1.27 (and with
GOEXPERIMENT=jsonv2for Go 1.26), this applies to all functions ofencoding/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:
- Issue #34154: encoding/json: string option (struct tag) on string field with SetEscapeHTML(false) escapes anyway
- PR #34127: encoding/json: fix and optimize marshal for quoted string
- Issue #34268: encoding/json: wrong encoding for json.Number field with string option (struct tag)
- PR #34269: encoding/json: make Number with the ,string option marshal with quotes
- PR #34272: encoding/json: validate strings when decoding into Number
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 ¶
var Version = "errchkjson version dev"
Functions ¶
func NewAnalyzer ¶
NewAnalyzer returns a new errchkjson analyzer.
Types ¶
This section is empty.