Documentation
¶
Overview ¶
Package json converts Go values to JSON and back, with the API of encoding/json/v2 of Go 1.27: code which imports encoding/json/v2 can import github.com/goccy/go-json/v2 instead, and code which imports encoding/json/jsontext can import github.com/goccy/go-json/jsontext.
It builds with every Go version this module supports, not only Go 1.27, and behaves as encoding/json/v2 of Go 1.27 does with any of them. Its types and functions are its own: they have the names, signatures and behavior of encoding/json/v2, but they are not aliases of it.
The encoder which a MarshalJSONTo method or a function of MarshalToFunc is given writes to an output of its own, which is checked when the method returns: the value fails if the method wrote other than one value at its place, or ended the object or the array its value is in. A call of MarshalEncode which fails writes nothing to the encoder, and fails the value of the method whether the method returns the error or not, also where encoding/json/v2, whose encoder is shared by the calls, succeeds by what the value wrote before it failed.
Index ¶
- Variables
- func GetOption[T any](opts Options, setter func(T) Options) (T, bool)
- func Marshal(in any, opts ...Options) ([]byte, error)
- func MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) error
- func MarshalOf[T any](in T, opts ...Options) ([]byte, error)
- func MarshalWrite(out io.Writer, in any, opts ...Options) error
- func MarshalWriteOf[T any](out io.Writer, in T, opts ...Options) error
- func Unmarshal(in []byte, out any, opts ...Options) error
- func UnmarshalDecode(in *jsontext.Decoder, out any, opts ...Options) error
- func UnmarshalDecodeOf[T any](in *jsontext.Decoder, out *T, opts ...Options) error
- func UnmarshalOf[T any](in []byte, out *T, opts ...Options) error
- func UnmarshalRead(in io.Reader, out any, opts ...Options) error
- func UnmarshalReadOf[T any](in io.Reader, out *T, opts ...Options) error
- type Marshaler
- type MarshalerTo
- type Marshalers
- type Options
- func DefaultOptionsV2() Options
- func Deterministic(v bool) Options
- func FormatNilMapAsNull(v bool) Options
- func FormatNilSliceAsNull(v bool) Options
- func JoinOptions(srcs ...Options) Options
- func MatchCaseInsensitiveNames(v bool) Options
- func OmitZeroStructFields(v bool) Options
- func RejectUnknownMembers(v bool) Options
- func StringifyNumbers(v bool) Options
- func WithMarshalers(v *Marshalers) Options
- func WithUnmarshalers(v *Unmarshalers) Options
- type SemanticError
- type Unmarshaler
- type UnmarshalerFrom
- type Unmarshalers
Constants ¶
This section is empty.
Variables ¶
var ErrUnknownName = ierrors.ErrUnknownName
ErrUnknownName reports that a JSON object member could not be unmarshaled because the name is not known to the target Go struct. It is wrapped directly by a SemanticError, whose JSONPointer points to the member:
var serr *json.SemanticError
if errors.As(err, &serr) && serr.Err == json.ErrUnknownName {
ptr := serr.JSONPointer // JSON pointer to the unknown member
name := ptr.LastToken() // the name itself
...
}
It is only reported if RejectUnknownMembers is true.
Functions ¶
func GetOption ¶
GetOption returns the value which opts has for the property that setter sets, and whether opts sets it. If it doesn't, the value is the zero value of T.
v, ok := json.GetOption(opts, json.Deterministic)
It is mostly for MarshalerTo and UnmarshalerFrom methods, and MarshalToFunc and UnmarshalFromFunc functions, which change the representation of a value by the options; those should usually ignore whether the property is set.
func Marshal ¶
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options). It does not terminate the output with a newline.
Type-specific marshal functions and methods take precedence over the default representation of a value. Functions or methods that operate on *T are only called when encoding a value of type T (by taking its address) or a non-nil value of *T. Marshal ensures that a value is always addressable (by boxing it on the heap if necessary) so that these functions and methods can be consistently called. For performance, it is recommended that Marshal be passed a non-nil pointer to the value.
The input value is encoded as JSON according the following rules:
If any type-specific functions in a WithMarshalers option match the value type, then those functions are called to encode the value. If all applicable functions return errors.ErrUnsupported, then the value is encoded according to subsequent rules.
If the value type implements MarshalerTo, then the MarshalJSONTo method is called to encode the value.
If the value type implements Marshaler, then the MarshalJSON method is called to encode the value.
If the value type implements encoding.TextAppender, then the AppendText method is called to encode the value and subsequently encode its result as a JSON string.
If the value type implements encoding.TextMarshaler, then the MarshalText method is called to encode the value and subsequently encode its result as a JSON string.
Otherwise, the value is encoded according to the value's type as described in detail below.
Most Go types have a default JSON representation as follows:
A Go boolean is encoded as a JSON boolean (e.g., true or false).
A Go string is encoded as a JSON string.
A Go []byte or [N]byte is encoded as a JSON string containing a binary value using Base 64 Encoding per RFC 4648, section 4.
A Go integer is encoded as a JSON number without fractions or exponents. If StringifyNumbers is specified or encoding a JSON object name, then the JSON number is encoded within a JSON string.
A Go float is encoded as a JSON number. If StringifyNumbers is specified or encoding a JSON object name, then the JSON number is encoded within a JSON string. Encoding a NaN or ±Inf results in a SemanticError.
A Go map is encoded as a JSON object, where each Go map key and value is recursively encoded as a name and value pair in the JSON object. The Go map key must encode as a JSON string, otherwise this results in a SemanticError. The Go map is traversed in a non-deterministic order. For deterministic encoding, consider using the Deterministic option. By default, a nil map is encoded as an empty JSON object, unless the FormatNilMapAsNull option is specified.
A Go struct is encoded as a JSON object. See the “JSON Representation of Go structs” section in the package-level documentation for more details.
A Go slice is encoded as a JSON array, where each Go slice element is recursively JSON-encoded as the elements of the JSON array. By default, a nil slice is encoded as an empty JSON array, unless the FormatNilSliceAsNull option is specified.
A Go array is encoded as a JSON array, where each Go array element is recursively JSON-encoded as the elements of the JSON array. The JSON array length is always identical to the Go array length.
A Go pointer is encoded as a JSON null if nil, otherwise it is the recursively JSON-encoded representation of the underlying value.
A Go interface is encoded as a JSON null if nil, otherwise it is the recursively JSON-encoded representation of the underlying value.
A Go time.Time is encoded as a JSON string containing the timestamp formatted in RFC 3339 with nanosecond precision.
A Go time.Duration currently has no default representation and results in a SemanticError.
All other Go types (e.g., complex numbers, channels, and functions) have no default representation and result in a SemanticError.
JSON cannot represent cyclic data structures and Marshal does not handle them.
func MarshalEncode ¶
MarshalEncode serializes a Go value into a jsontext.Encoder according to the provided marshal or encode options (while ignoring unmarshal or decode options). The options provided take precedence over options already applied on the jsontext.Encoder and only apply for the duration of the marshal call.
See Marshal for details about the conversion of a Go value into JSON.
func MarshalOf ¶
MarshalOf returns the JSON encoding of in, as Marshal does.
Marshal takes its argument as an interface value, which a value that is not a pointer, a map or a channel is copied to the heap for. MarshalOf takes the value by its type, and copies it to a value in the heap which is reused, so that it encodes the value without an allocation other than the one of the result. See MarshalWriteOf for the encoding without the result.
func MarshalWrite ¶
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options). It does not terminate the output with a newline. See Marshal for details about the conversion of a Go value into JSON.
func MarshalWriteOf ¶
MarshalWriteOf writes the JSON encoding of in to out, as MarshalWrite does. It takes the value by its type, as MarshalOf does: the encoding is written from a buffer which is reused, without the copy of the result, so that a value is written without an allocation, unless the writer or a method of the value makes one.
func Unmarshal ¶
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options). The input must be a single JSON value with optional whitespace interspersed. The output must be a non-nil pointer.
Type-specific unmarshal functions and methods take precedence over the default representation of a value. Functions or methods that operate on *T are only called when decoding a value of type T (by taking its address) or a non-nil value of *T. Unmarshal ensures that a value is always addressable (by boxing it on the heap if necessary) so that these functions and methods can be consistently called. If a value must be shallow copied to call a pointer-receiver Unmarshaler, UnmarshalerFrom, or encoding.TextUnmarshaler method, then any mutations performed by the method are shallow copied back into the destination value.
The input is decoded into the output according to the following rules:
If any type-specific functions in a WithUnmarshalers option match the value type, then those functions are called to decode the JSON value. If all applicable functions return errors.ErrUnsupported, then the input is decoded according to subsequent rules.
If the value type implements UnmarshalerFrom, then the UnmarshalJSONFrom method is called to decode the JSON value. If the method returns errors.ErrUnsupported, then the input is decoded according to subsequent rules.
If the value type implements Unmarshaler, then the UnmarshalJSON method is called to decode the JSON value.
If the value type implements encoding.TextUnmarshaler, then the input is decoded as a JSON string and the UnmarshalText method is called with the decoded string value. This fails with a SemanticError if the input is not a JSON string.
Otherwise, the JSON value is decoded according to the value's type as described in detail below.
The input is decoded into the output as follows:
A Go boolean is decoded from a JSON boolean (e.g., true or false).
A Go string is decoded from a JSON string.
A Go []byte or [N]byte is decoded from a JSON string containing a binary value using Base 64 Encoding per RFC 4648, section 4. When decoding into a non-nil []byte, the slice length is reset to zero and the decoded input is appended to it. When decoding into a [N]byte, the input must decode to exactly N bytes, otherwise it fails with a SemanticError.
A Go integer is decoded from a JSON number. It must be decoded from a JSON string containing a JSON number if StringifyNumbers is specified or decoding a JSON object name. It fails with a SemanticError if the JSON number has a fractional or exponent component. It also fails if it overflows the representation of the Go integer type.
A Go float is decoded from a JSON number. It must be decoded from a JSON string containing a JSON number if StringifyNumbers is specified or decoding a JSON object name. It fails if it overflows the representation of the Go float type.
A Go map is decoded from a JSON object, where each JSON object name and value pair is recursively decoded as the Go map key and value. Maps are not cleared. If the Go map is nil, then a new map is allocated to decode into. If the decoded key matches an existing Go map entry, the entry value is reused by decoding the JSON object value into it.
A Go struct is decoded from a JSON object. See the “JSON Representation of Go structs” section in the package-level documentation for more details.
A Go slice is decoded from a JSON array, where each JSON element is recursively decoded and appended to the Go slice. Before appending into a Go slice, a new slice is allocated if it is nil, otherwise the slice length is reset to zero.
A Go array is decoded from a JSON array, where each JSON array element is recursively decoded as each corresponding Go array element. Each Go array element is zeroed before decoding into it. It fails with a SemanticError if the JSON array does not contain the exact same number of elements as the Go array.
A Go pointer is decoded based on the JSON kind and underlying Go type. If the input is a JSON null, then this stores a nil pointer. Otherwise, it allocates a new underlying value if the pointer is nil, and recursively JSON decodes into the underlying value.
A Go interface is decoded based on the JSON kind and underlying Go type. If the input is a JSON null, then this stores a nil interface value. Otherwise, a nil interface value of an empty interface type is initialized with a zero Go bool, string, float64, map[string]any, or []any if the input is a JSON boolean, string, number, object, or array, respectively. If the interface value is still nil, then this fails with a SemanticError since decoding could not determine an appropriate Go type to decode into. Otherwise an underlying value exists and it recursively decodes the JSON input into it.
A Go time.Time is decoded from a JSON string containing the time formatted in RFC 3339 with nanosecond precision.
A Go time.Duration currently has no default representation and results in a SemanticError.
A JSON null is decoded into any of the other values above as its zero value.
All other Go types (e.g., complex numbers, channels, and functions) have no default representation and result in a SemanticError.
func UnmarshalDecode ¶
UnmarshalDecode deserializes a Go value from a jsontext.Decoder according to the provided unmarshal or decode options (while ignoring marshal or encode options). The options provided take precedence over options already applied on the jsontext.Decoder and only apply for the duration of the unmarshal call.
The input may be a stream of zero or more JSON values. UnmarshalDecode unmarshals only the next JSON value in the stream. If there are no more top-level JSON values, it reports io.EOF. The output must be a non-nil pointer. See Unmarshal for details about the conversion of JSON into a Go value.
The value is read from the input of the decoder as UnmarshalRead reads it, with bounded memory, or, for the decoder which an UnmarshalJSONFrom method or a function of UnmarshalFromFunc is given, as Unmarshal or UnmarshalRead reads it. After a SemanticError, the decoder goes on after the value, whose rest is read, and checked by its grammar, or, if the rest has an error, every read of the decoder fails with that error; but not after the error of a method or a function which read a jsontext.Decoder of the value from a reader. After any other error, the decoder is where it was before the value, as after an error of Decoder.ReadValue, but if the decoder read the value from a reader past what it had read itself and dropped the start of the value, which it reads with bounded memory: every read of the decoder fails with the error then.
func UnmarshalDecodeOf ¶
UnmarshalDecodeOf decodes the next value of a jsontext.Decoder into the value out points to, as UnmarshalDecode does, through a value in the heap which is reused, as UnmarshalOf does.
func UnmarshalOf ¶
UnmarshalOf decodes a []byte input into the value out points to, as Unmarshal does.
Unmarshal takes its output as an interface value, and the decoder refers to the value by its address, so the value always escapes to the heap. UnmarshalOf takes the pointer by its type and never gives it to the decoder: it copies *out to a value in the heap which is reused, decodes into that value, and copies the result back to *out, also after an error. So out may point to a variable on the stack of the caller, and a value which needs no allocation of its own (no pointer, slice, map or string to fill) is decoded without an allocation: a string is a copy of its own, as Unmarshal makes it.
A value is copied twice, so a large value is faster with Unmarshal when it is in the heap anyway. As the result is a copy, an UnmarshalJSONFrom, UnmarshalJSON or UnmarshalText method of a type in the value must not keep the address of its receiver, which is the address of the copy.
func UnmarshalRead ¶
UnmarshalRead deserializes a Go value from an io.Reader according to the provided unmarshal and decode options (while ignoring marshal or encode options). The input must be a single JSON value with optional whitespace interspersed. It consumes the entirety of io.Reader until io.EOF is encountered, without reporting an error for EOF. The output must be a non-nil pointer. See Unmarshal for details about the conversion of JSON into a Go value.
The input is read 512 bytes at a time. A value which the bytes read hold whole is decoded as Unmarshal decodes it, and an object or an array which they don't is decoded member by member and element by element as it is read, so that the memory which the input takes doesn't grow with its size. Only a token longer than a read, and a value which a method or a function reads whole, as UnmarshalJSON, UnmarshalText, a function of UnmarshalFunc or a jsontext.Value, are held whole, as encoding/json/v2 holds them.
Types ¶
type Marshaler ¶
Marshaler is implemented by types that can marshal themselves. It is recommended that types implement MarshalerTo unless the implementation is trying to avoid directly depending on the jsontext package.
Implementations should return a buffer that is safe for the caller to retain and potentially mutate.
Implementations must not return errors.ErrUnsupported.
If the returned error is a SemanticError, then unpopulated fields of the error may be populated by this package with additional context. Errors of other types are wrapped within a SemanticError.
Implementations should assume Deterministic is true and return deterministic output.
type MarshalerTo ¶
MarshalerTo is implemented by types that can marshal themselves. It is recommended that types implement MarshalerTo instead of Marshaler since it is both more performant and more flexible. If a type implements both Marshaler and MarshalerTo, then MarshalerTo takes precedence. In such a case, both implementations should aim to have equivalent behavior for the default marshal options.
The implementation must write only one JSON value to the Encoder. Alternatively, it may return errors.ErrUnsupported without mutating the Encoder. This package calling the method will use the next available JSON representation for the receiver type, as described in Marshal. Implementations must not retain the pointer to jsontext.Encoder.
If the returned error is a SemanticError, then unpopulated fields of the error may be populated by this package with additional context. Errors of other types are wrapped within a SemanticError, except for IO errors.
The MarshalJSONTo method should not be called directly as it may return sentinel errors that need special handling. Users should instead call MarshalEncode, which handles such cases.
Implementations should inspect the marshal options from jsontext.Encoder.Options and adjust behavior to respect the options as necessary.
The following options may be relevant to MarshalerTo implementations:
- Deterministic: if the implementation may produce non-deterministic output
- StringifyNumbers: if the type is represented as a JSON number
Several options, such as FormatNilSliceAsNull, apply only to native Go types. Thus, these options are typically not directly relevant to MarshalerTo implementations. However, types representing a composite type should marshal contained types using MarshalEncode to ensure these options apply to the contained types. Similarly, WithMarshalers may influence marshaling of any contained type within a composite type.
All other options are automatically handled outside of the MarshalerTo implementation, and thus are not relevant to implementations.
type Marshalers ¶
type Marshalers struct {
// contains filtered or unexported fields
}
Marshalers is a list of functions that may override the marshal behavior of specific types. Populate WithMarshalers to use it with Marshal, MarshalWrite, or MarshalEncode. A nil *Marshalers is equivalent to an empty list. There are no exported fields or methods on Marshalers.
func JoinMarshalers ¶
func JoinMarshalers(ms ...*Marshalers) *Marshalers
JoinMarshalers constructs a flattened list of marshal functions. If multiple functions in the list are applicable for a value of a given type, then those earlier in the list take precedence over those that come later. If a function returns errors.ErrUnsupported, then the next applicable function is called, otherwise the default marshaling behavior is used.
For example, these two are equivalent:
JoinMarshalers(f0, JoinMarshalers(f1, f2), f3) JoinMarshalers(f0, f1, f2, f3)
func MarshalFunc ¶
func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers
MarshalFunc constructs a type-specific marshaler that specifies how to marshal values of type T. T can be any type except a named pointer. The function is always provided with a non-nil pointer value if T is an interface or pointer type.
Implementations must follow the requirements of Marshaler.
Implementations must not retain the value of T.
func MarshalToFunc ¶
func MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers
MarshalToFunc constructs a type-specific marshaler that specifies how to marshal values of type T. T can be any type except a named pointer. The function is always provided with a non-nil pointer value if T is an interface or pointer type.
Implementations must follow the requirements of MarshalerTo.
Implementations must not retain the pointer to jsontext.Encoder or the value of T.
type Options ¶
Options configures Marshal, MarshalWrite, MarshalEncode, Unmarshal, UnmarshalRead and UnmarshalDecode. It is the same type as jsontext.Options and github.com/goccy/go-json.Options, so that the options of the jsontext package and of github.com/goccy/go-json may be given to them as well, and the options of this package to jsontext.NewEncoder and jsontext.NewDecoder. In a list of options, an option given later overrides a property set by an earlier one.
The options of this package:
- StringifyNumbers affects marshaling and unmarshaling
- Deterministic affects marshaling only
- FormatNilSliceAsNull affects marshaling only
- FormatNilMapAsNull affects marshaling only
- OmitZeroStructFields affects marshaling only
- MatchCaseInsensitiveNames affects marshaling and unmarshaling
- RejectUnknownMembers affects unmarshaling only
- WithMarshalers affects marshaling only
- WithUnmarshalers affects unmarshaling only
An option which doesn't affect an operation is ignored by it.
func DefaultOptionsV2 ¶
func DefaultOptionsV2() Options
DefaultOptionsV2 sets every option of the v2 semantics: the options which the v1 json package sets by default, all false. Other options are not set.
func Deterministic ¶
Deterministic specifies that marshaling the same value always writes the same bytes: for example, the entries of a Go map are written in the order of their keys. Of the values of the Go types, the output is the same for the same binary, but may differ between builds of a program, as a newer version may change the representation. It is not a canonical form: Deterministic and the canonical form of RFC 8785 are different things.
This affects marshaling only.
func FormatNilMapAsNull ¶
FormatNilMapAsNull specifies that a nil Go map is the JSON null, rather than an empty JSON object.
This affects marshaling only.
func FormatNilSliceAsNull ¶
FormatNilSliceAsNull specifies that a nil Go slice is the JSON null, rather than an empty JSON array (or an empty JSON string, of a ~[]byte).
This affects marshaling only.
func JoinOptions ¶
JoinOptions returns the options of srcs as a single Options, in which a property set by a later option overrides the one of an earlier option.
func MatchCaseInsensitiveNames ¶
MatchCaseInsensitiveNames specifies that the names of the members of a JSON object are matched to the fields of a Go struct case-insensitively. If a name matches more than one field, the field whose name is the same is taken, and if none is, it is an error. A field with the case:strict or case:ignore option always matches its name case-sensitively or case-insensitively, whatever this option is.
This affects marshaling and unmarshaling: when marshaling, the check of the duplicate names of the fields follows it.
func OmitZeroStructFields ¶
OmitZeroStructFields specifies that the fields of a Go struct which are zero are left out: a value is zero if its type has an "IsZero() bool" method which returns true, or, without the method, if it is the zero value of its type. It is the omitzero option on every field of every struct.
This affects marshaling only.
func RejectUnknownMembers ¶
RejectUnknownMembers specifies that a member of a JSON object which matches no field of the Go struct is an error when unmarshaling.
This affects unmarshaling only.
func StringifyNumbers ¶
StringifyNumbers specifies that a Go value which would be a JSON number is a JSON string of that number. When unmarshaling, the value is read from a JSON string which holds only the number, without white space.
The string option of a struct field applies it to the field only.
This affects marshaling and unmarshaling.
func WithMarshalers ¶
func WithMarshalers(v *Marshalers) Options
WithMarshalers specifies a list of type-specific marshalers to use, which can be used to override the default marshal behavior for values of particular types.
This only affects marshaling and is ignored when unmarshaling.
func WithUnmarshalers ¶
func WithUnmarshalers(v *Unmarshalers) Options
WithUnmarshalers specifies a list of type-specific unmarshalers to use, which can be used to override the default unmarshal behavior for values of particular types.
This only affects unmarshaling and is ignored when marshaling.
type SemanticError ¶
type SemanticError struct {
// ByteOffset is the offset in the input or output at or after which the error occurred.
ByteOffset int64
// JSONPointer points to the JSON value within which the error occurred (see RFC 6901).
JSONPointer jsontext.Pointer
// JSONKind is the kind of the JSON value which could not be handled. It may be zero if it is unknown.
JSONKind jsontext.Kind
// JSONValue is the JSON number or string which could not be unmarshaled. It is not set by marshaling.
JSONValue jsontext.Value
// GoType is the Go type which could not be handled. It may be nil if it is unknown.
GoType reflect.Type
// Err is the underlying error. It may be nil.
Err error
// contains filtered or unexported fields
}
SemanticError describes an error determining the meaning of JSON data as Go data, or vice versa.
If a Marshaler, MarshalerTo, Unmarshaler or UnmarshalerFrom method returns a SemanticError when called by this package, its ByteOffset, JSONPointer and GoType are filled in by the caller if they are the zero value.
The contents of this error, as this package makes it, may change over time.
func (*SemanticError) Error ¶
func (e *SemanticError) Error() string
func (*SemanticError) Unwrap ¶
func (e *SemanticError) Unwrap() error
type Unmarshaler ¶
Unmarshaler is implemented by types that can unmarshal themselves. It is recommended that types implement UnmarshalerFrom unless the implementation is trying to avoid a direct dependency on the "jsontext" package.
The input can be assumed to be a valid encoding of a JSON value if called from unmarshal functionality in this package. It is recommended that UnmarshalJSON implement merge semantics when unmarshaling into a pre-populated value, as described in Unmarshal.
Implementations must not retain or mutate the input []byte.
Implementations must not return errors.ErrUnsupported.
If the returned error is a SemanticError, then unpopulated fields of the error may be populated by this package with additional context. Errors of other types are wrapped within a SemanticError.
type UnmarshalerFrom ¶
UnmarshalerFrom is implemented by types that can unmarshal themselves. It is recommended that types implement UnmarshalerFrom instead of Unmarshaler since this is both more performant and more flexible. If a type implements both Unmarshaler and UnmarshalerFrom, then UnmarshalerFrom takes precedence. In such a case, both implementations should aim to have equivalent behavior for the default unmarshal options.
The implementation must read only one JSON value from the Decoder. It is recommended that UnmarshalJSONFrom implement merge semantics when unmarshaling into a pre-populated value, as described in Unmarshal. Alternatively, it may return errors.ErrUnsupported without mutating the Decoder. The "json" package calling the method will use the next available JSON representation for the receiver type. Implementations must not retain the pointer to jsontext.Decoder.
If the returned error is a SemanticError, then unpopulated fields of the error may be populated by this package with additional context. Errors of other types are wrapped within a SemanticError, except for jsontext.SyntacticErrors and IO errors.
The UnmarshalJSONFrom method should not be called directly as it may return sentinel errors that need special handling. Users should instead call UnmarshalDecode, which handles such cases.
Implementations should inspect the unmarshal options from jsontext.Decoder.Options and adjust behavior to respect the options as necessary.
The following options may be relevant to UnmarshalerFrom implementations:
- StringifyNumbers: if the type is represented as a JSON number
Several options, such as FormatNilSliceAsNull, apply only to native Go types. Thus, these options are typically not directly relevant to UnmarshalerFrom implementations. However, types representing a composite type should unmarshal contained types using UnmarshalDecode to ensure these options apply to the contained types. Similarly, WithUnmarshalers may influence unmarshaling of any contained type within a composite type.
All other options are automatically handled outside of the UnmarshalerFrom implementation, and thus are not relevant to implementations.
type Unmarshalers ¶
type Unmarshalers struct {
// contains filtered or unexported fields
}
Unmarshalers is a list of functions that may override the unmarshal behavior of specific types. Populate WithUnmarshalers to use it with Unmarshal, UnmarshalRead, or UnmarshalDecode. A nil *Unmarshalers is equivalent to an empty list. There are no exported fields or methods on Unmarshalers.
func JoinUnmarshalers ¶
func JoinUnmarshalers(us ...*Unmarshalers) *Unmarshalers
JoinUnmarshalers constructs a flattened list of unmarshal functions. If multiple functions in the list are applicable for a value of a given type, then those earlier in the list take precedence over those that come later. If a function returns errors.ErrUnsupported, then the next applicable function is called, otherwise the default unmarshaling behavior is used.
For example, these two are equivalent:
JoinUnmarshalers(u0, JoinUnmarshalers(u1, u2), u3) JoinUnmarshalers(u0, u1, u2, u3)
func UnmarshalFromFunc ¶
func UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers
UnmarshalFromFunc constructs a type-specific unmarshaler that specifies how to unmarshal values of type T. T must be an unnamed pointer or an interface type. The function is always provided with a non-nil pointer value.
Implementations must follow the requirements of UnmarshalerFrom.
Implementations must not retain the pointer to jsontext.Decoder or the value of T.
func UnmarshalFunc ¶
func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers
UnmarshalFunc constructs a type-specific unmarshaler that specifies how to unmarshal values of type T. T must be an unnamed pointer or an interface type. The function is always provided with a non-nil pointer value.
Implementations must follow the requirements of Unmarshaler.
Implementations must not retain the input []byte or the value of T.