Debian Codegraph @

alias.go

raw symbols SCIP
1 // Copyright 2025 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Code generated by alias_gen.go; DO NOT EDIT.
6
7 //go:build goexperiment.jsonv2 && go1.25
8
9 // Package json implements semantic processing of JSON as specified in RFC 8259.
10 // JSON is a simple data interchange format that can represent
11 // primitive data types such as booleans, strings, and numbers,
12 // in addition to structured data types such as objects and arrays.
13 //
14 // [Marshal] and [Unmarshal] encode and decode Go values
15 // to/from JSON text contained within a []byte.
16 // [MarshalWrite] and [UnmarshalRead] operate on JSON text
17 // by writing to or reading from an [io.Writer] or [io.Reader].
18 // [MarshalEncode] and [UnmarshalDecode] operate on JSON text
19 // by encoding to or decoding from a [jsontext.Encoder] or [jsontext.Decoder].
20 // [Options] may be passed to each of the marshal or unmarshal functions
21 // to configure the semantic behavior of marshaling and unmarshaling
22 // (i.e., alter how JSON data is understood as Go data and vice versa).
23 // [jsontext.Options] may also be passed to the marshal or unmarshal functions
24 // to configure the syntactic behavior of encoding or decoding.
25 //
26 // The data types of JSON are mapped to/from the data types of Go based on
27 // the closest logical equivalent between the two type systems. For example,
28 // a JSON boolean corresponds with a Go bool,
29 // a JSON string corresponds with a Go string,
30 // a JSON number corresponds with a Go int, uint or float,
31 // a JSON array corresponds with a Go slice or array, and
32 // a JSON object corresponds with a Go struct or map.
33 // See the documentation on [Marshal] and [Unmarshal] for a comprehensive list
34 // of how the JSON and Go type systems correspond.
35 //
36 // Arbitrary Go types can customize their JSON representation by implementing
37 // [Marshaler], [MarshalerTo], [Unmarshaler], or [UnmarshalerFrom].
38 // This provides authors of Go types with control over how their types are
39 // serialized as JSON. Alternatively, users can implement functions that match
40 // [MarshalFunc], [MarshalToFunc], [UnmarshalFunc], or [UnmarshalFromFunc]
41 // to specify the JSON representation for arbitrary types.
42 // This provides callers of JSON functionality with control over
43 // how any arbitrary type is serialized as JSON.
44 //
45 // # JSON Representation of Go structs
46 //
47 // A Go struct is naturally represented as a JSON object,
48 // where each Go struct field corresponds with a JSON object member.
49 // When marshaling, all Go struct fields are recursively encoded in depth-first
50 // order as JSON object members except those that are ignored or omitted.
51 // When unmarshaling, JSON object members are recursively decoded
52 // into the corresponding Go struct fields.
53 // Object members that do not match any struct fields,
54 // also known as “unknown members”, are ignored by default or rejected
55 // if [RejectUnknownMembers] is specified.
56 //
57 // The representation of each struct field can be customized in the
58 // "json" struct field tag, where the tag is a comma separated list of options.
59 // As a special case, if the entire tag is `json:"-"`,
60 // then the field is ignored with regard to its JSON representation.
61 // Some options also have equivalent behavior controlled by a caller-specified [Options].
62 // Field-specified options take precedence over caller-specified options.
63 //
64 // The first option is the JSON object name override for the Go struct field.
65 // If the name is not specified, then the Go struct field name
66 // is used as the JSON object name. JSON names containing commas or quotes,
67 // or names identical to "" or "-", can be specified using
68 // a single-quoted string literal, where the syntax is identical to
69 // the Go grammar for a double-quoted string literal,
70 // but instead uses single quotes as the delimiters.
71 // By default, unmarshaling uses case-sensitive matching to identify
72 // the Go struct field associated with a JSON object name.
73 //
74 // After the name, the following tag options are supported:
75 //
76 // - omitzero: When marshaling, the "omitzero" option specifies that
77 // the struct field should be omitted if the field value is zero
78 // as determined by the "IsZero() bool" method if present,
79 // otherwise based on whether the field is the zero Go value.
80 // This option has no effect when unmarshaling.
81 //
82 // - omitempty: When marshaling, the "omitempty" option specifies that
83 // the struct field should be omitted if the field value would have been
84 // encoded as a JSON null, empty string, empty object, or empty array.
85 // This option has no effect when unmarshaling.
86 //
87 // - string: The "string" option specifies that [StringifyNumbers]
88 // be set when marshaling or unmarshaling a struct field value.
89 // This causes numeric types to be encoded as a JSON number
90 // within a JSON string, and to be decoded from a JSON string
91 // containing the JSON number without any surrounding whitespace.
92 // This extra level of encoding is often necessary since
93 // many JSON parsers cannot precisely represent 64-bit integers.
94 //
95 // - case: When unmarshaling, the "case" option specifies how
96 // JSON object names are matched with the JSON name for Go struct fields.
97 // The option is a key-value pair specified as "case:value" where
98 // the value must either be 'ignore' or 'strict'.
99 // The 'ignore' value specifies that matching is case-insensitive
100 // where dashes and underscores are also ignored. If multiple fields match,
101 // the first declared field in breadth-first order takes precedence.
102 // The 'strict' value specifies that matching is case-sensitive.
103 // This takes precedence over the [MatchCaseInsensitiveNames] option.
104 //
105 // - inline: The "inline" option specifies that
106 // the JSON representable content of this field type is to be promoted
107 // as if they were specified in the parent struct.
108 // It is the JSON equivalent of Go struct embedding.
109 // A Go embedded field is implicitly inlined unless an explicit JSON name
110 // is specified. The inlined field must be a Go struct
111 // (that does not implement any JSON methods), [jsontext.Value],
112 // map[~string]T, or an unnamed pointer to such types. When marshaling,
113 // inlined fields from a pointer type are omitted if it is nil.
114 // Inlined fields of type [jsontext.Value] and map[~string]T are called
115 // “inlined fallbacks” as they can represent all possible
116 // JSON object members not directly handled by the parent struct.
117 // Only one inlined fallback field may be specified in a struct,
118 // while many non-fallback fields may be specified. This option
119 // must not be specified with any other option (including the JSON name).
120 //
121 // - format: The "format" option specifies a format flag
122 // used to specialize the formatting of the field value.
123 // The option is a key-value pair specified as "format:value" where
124 // the value must be either a literal consisting of letters and numbers
125 // (e.g., "format:RFC3339") or a single-quoted string literal
126 // (e.g., "format:'2006-01-02'"). The interpretation of the format flag
127 // is determined by the struct field type.
128 //
129 // The "omitzero" and "omitempty" options are mostly semantically identical.
130 // The former is defined in terms of the Go type system,
131 // while the latter in terms of the JSON type system.
132 // Consequently they behave differently in some circumstances.
133 // For example, only a nil slice or map is omitted under "omitzero", while
134 // an empty slice or map is omitted under "omitempty" regardless of nilness.
135 // The "omitzero" option is useful for types with a well-defined zero value
136 // (e.g., [net/netip.Addr]) or have an IsZero method (e.g., [time.Time.IsZero]).
137 //
138 // Every Go struct corresponds to a list of JSON representable fields
139 // which is constructed by performing a breadth-first search over
140 // all struct fields (excluding unexported or ignored fields),
141 // where the search recursively descends into inlined structs.
142 // The set of non-inlined fields in a struct must have unique JSON names.
143 // If multiple fields all have the same JSON name, then the one
144 // at shallowest depth takes precedence and the other fields at deeper depths
145 // are excluded from the list of JSON representable fields.
146 // If multiple fields at the shallowest depth have the same JSON name,
147 // but exactly one is explicitly tagged with a JSON name,
148 // then that field takes precedence and all others are excluded from the list.
149 // This is analogous to Go visibility rules for struct field selection
150 // with embedded struct types.
151 //
152 // Marshaling or unmarshaling a non-empty struct
153 // without any JSON representable fields results in a [SemanticError].
154 // Unexported fields must not have any `json` tags except for `json:"-"`.
155 //
156 // # Security Considerations
157 //
158 // JSON is frequently used as a data interchange format to communicate
159 // between different systems, possibly implemented in different languages.
160 // For interoperability and security reasons, it is important that
161 // all implementations agree upon the semantic meaning of the data.
162 //
163 // [For example, suppose we have two micro-services.]
164 // The first service is responsible for authenticating a JSON request,
165 // while the second service is responsible for executing the request
166 // (having assumed that the prior service authenticated the request).
167 // If an attacker were able to maliciously craft a JSON request such that
168 // both services believe that the same request is from different users,
169 // it could bypass the authenticator with valid credentials for one user,
170 // but maliciously perform an action on behalf of a different user.
171 //
172 // According to RFC 8259, there unfortunately exist many JSON texts
173 // that are syntactically valid but semantically ambiguous.
174 // For example, the standard does not define how to interpret duplicate
175 // names within an object.
176 //
177 // The v1 [encoding/json] and [encoding/json/v2] packages
178 // interpret some inputs in different ways. In particular:
179 //
180 // - The standard specifies that JSON must be encoded using UTF-8.
181 // By default, v1 replaces invalid bytes of UTF-8 in JSON strings
182 // with the Unicode replacement character,
183 // while v2 rejects inputs with invalid UTF-8.
184 // To change the default, specify the [jsontext.AllowInvalidUTF8] option.
185 // The replacement of invalid UTF-8 is a form of data corruption
186 // that alters the precise meaning of strings.
187 //
188 // - The standard does not specify a particular behavior when
189 // duplicate names are encountered within a JSON object,
190 // which means that different implementations may behave differently.
191 // By default, v1 allows for the presence of duplicate names,
192 // while v2 rejects duplicate names.
193 // To change the default, specify the [jsontext.AllowDuplicateNames] option.
194 // If allowed, object members are processed in the order they are observed,
195 // meaning that later values will replace or be merged into prior values,
196 // depending on the Go value type.
197 //
198 // - The standard defines a JSON object as an unordered collection of name/value pairs.
199 // While ordering can be observed through the underlying [jsontext] API,
200 // both v1 and v2 generally avoid exposing the ordering.
201 // No application should semantically depend on the order of object members.
202 // Allowing duplicate names is a vector through which ordering of members
203 // can accidentally be observed and depended upon.
204 //
205 // - The standard suggests that JSON object names are typically compared
206 // based on equality of the sequence of Unicode code points,
207 // which implies that comparing names is often case-sensitive.
208 // When unmarshaling a JSON object into a Go struct,
209 // by default, v1 uses a (loose) case-insensitive match on the name,
210 // while v2 uses a (strict) case-sensitive match on the name.
211 // To change the default, specify the [MatchCaseInsensitiveNames] option.
212 // The use of case-insensitive matching provides another vector through
213 // which duplicate names can occur. Allowing case-insensitive matching
214 // means that v1 or v2 might interpret JSON objects differently from most
215 // other JSON implementations (which typically use a case-sensitive match).
216 //
217 // - The standard does not specify a particular behavior when
218 // an unknown name in a JSON object is encountered.
219 // When unmarshaling a JSON object into a Go struct, by default
220 // both v1 and v2 ignore unknown names and their corresponding values.
221 // To change the default, specify the [RejectUnknownMembers] option.
222 //
223 // - The standard suggests that implementations may use a float64
224 // to represent a JSON number. Consequently, large JSON integers
225 // may lose precision when stored as a floating-point type.
226 // Both v1 and v2 correctly preserve precision when marshaling and
227 // unmarshaling a concrete integer type. However, even if v1 and v2
228 // preserve precision for concrete types, other JSON implementations
229 // may not be able to preserve precision for outputs produced by v1 or v2.
230 // The `string` tag option can be used to specify that an integer type
231 // is to be quoted within a JSON string to avoid loss of precision.
232 // Furthermore, v1 and v2 may still lose precision when unmarshaling
233 // into an any interface value, where unmarshal uses a float64
234 // by default to represent a JSON number.
235 // To change the default, specify the [WithUnmarshalers] option
236 // with a custom unmarshaler that pre-populates the interface value
237 // with a concrete Go type that can preserve precision.
238 //
239 // RFC 8785 specifies a canonical form for any JSON text,
240 // which explicitly defines specific behaviors that RFC 8259 leaves undefined.
241 // In theory, if a text can successfully [jsontext.Value.Canonicalize]
242 // without changing the semantic meaning of the data, then it provides a
243 // greater degree of confidence that the data is more secure and interoperable.
244 //
245 // The v2 API generally chooses more secure defaults than v1,
246 // but care should still be taken with large integers or unknown members.
247 //
248 // [For example, suppose we have two micro-services.]: https://www.youtube.com/watch?v=avilmOcHKHE&t=1057s
249 package json
250
251 import (
252 "encoding/json/jsontext"
253 "encoding/json/v2"
254 "io"
255 )
256
257 // Marshal serializes a Go value as a []byte according to the provided
258 // marshal and encode options (while ignoring unmarshal or decode options).
259 // It does not terminate the output with a newline.
260 //
261 // Type-specific marshal functions and methods take precedence
262 // over the default representation of a value.
263 // Functions or methods that operate on *T are only called when encoding
264 // a value of type T (by taking its address) or a non-nil value of *T.
265 // Marshal ensures that a value is always addressable
266 // (by boxing it on the heap if necessary) so that
267 // these functions and methods can be consistently called. For performance,
268 // it is recommended that Marshal be passed a non-nil pointer to the value.
269 //
270 // The input value is encoded as JSON according the following rules:
271 //
272 // - If any type-specific functions in a [WithMarshalers] option match
273 // the value type, then those functions are called to encode the value.
274 // If all applicable functions return [errors.ErrUnsupported],
275 // then the value is encoded according to subsequent rules.
276 //
277 // - If the value type implements [MarshalerTo],
278 // then the MarshalJSONTo method is called to encode the value.
279 // If the method returns [errors.ErrUnsupported],
280 // then the input is encoded according to subsequent rules.
281 //
282 // - If the value type implements [Marshaler],
283 // then the MarshalJSON method is called to encode the value.
284 //
285 // - If the value type implements [encoding.TextAppender],
286 // then the AppendText method is called to encode the value and
287 // subsequently encode its result as a JSON string.
288 //
289 // - If the value type implements [encoding.TextMarshaler],
290 // then the MarshalText method is called to encode the value and
291 // subsequently encode its result as a JSON string.
292 //
293 // - Otherwise, the value is encoded according to the value's type
294 // as described in detail below.
295 //
296 // Most Go types have a default JSON representation.
297 // Certain types support specialized formatting according to
298 // a format flag optionally specified in the Go struct tag
299 // for the struct field that contains the current value
300 // (see the “JSON Representation of Go structs” section for more details).
301 //
302 // The representation of each type is as follows:
303 //
304 // - A Go boolean is encoded as a JSON boolean (e.g., true or false).
305 // It does not support any custom format flags.
306 //
307 // - A Go string is encoded as a JSON string.
308 // It does not support any custom format flags.
309 //
310 // - A Go []byte or [N]byte is encoded as a JSON string containing
311 // the binary value encoded using RFC 4648.
312 // If the format is "base64" or unspecified, then this uses RFC 4648, section 4.
313 // If the format is "base64url", then this uses RFC 4648, section 5.
314 // If the format is "base32", then this uses RFC 4648, section 6.
315 // If the format is "base32hex", then this uses RFC 4648, section 7.
316 // If the format is "base16" or "hex", then this uses RFC 4648, section 8.
317 // If the format is "array", then the bytes value is encoded as a JSON array
318 // where each byte is recursively JSON-encoded as each JSON array element.
319 //
320 // - A Go integer is encoded as a JSON number without fractions or exponents.
321 // If [StringifyNumbers] is specified or encoding a JSON object name,
322 // then the JSON number is encoded within a JSON string.
323 // It does not support any custom format flags.
324 //
325 // - A Go float is encoded as a JSON number.
326 // If [StringifyNumbers] is specified or encoding a JSON object name,
327 // then the JSON number is encoded within a JSON string.
328 // If the format is "nonfinite", then NaN, +Inf, and -Inf are encoded as
329 // the JSON strings "NaN", "Infinity", and "-Infinity", respectively.
330 // Otherwise, the presence of non-finite numbers results in a [SemanticError].
331 //
332 // - A Go map is encoded as a JSON object, where each Go map key and value
333 // is recursively encoded as a name and value pair in the JSON object.
334 // The Go map key must encode as a JSON string, otherwise this results
335 // in a [SemanticError]. The Go map is traversed in a non-deterministic order.
336 // For deterministic encoding, consider using the [Deterministic] option.
337 // If the format is "emitnull", then a nil map is encoded as a JSON null.
338 // If the format is "emitempty", then a nil map is encoded as an empty JSON object,
339 // regardless of whether [FormatNilMapAsNull] is specified.
340 // Otherwise by default, a nil map is encoded as an empty JSON object.
341 //
342 // - A Go struct is encoded as a JSON object.
343 // See the “JSON Representation of Go structs” section
344 // in the package-level documentation for more details.
345 //
346 // - A Go slice is encoded as a JSON array, where each Go slice element
347 // is recursively JSON-encoded as the elements of the JSON array.
348 // If the format is "emitnull", then a nil slice is encoded as a JSON null.
349 // If the format is "emitempty", then a nil slice is encoded as an empty JSON array,
350 // regardless of whether [FormatNilSliceAsNull] is specified.
351 // Otherwise by default, a nil slice is encoded as an empty JSON array.
352 //
353 // - A Go array is encoded as a JSON array, where each Go array element
354 // is recursively JSON-encoded as the elements of the JSON array.
355 // The JSON array length is always identical to the Go array length.
356 // It does not support any custom format flags.
357 //
358 // - A Go pointer is encoded as a JSON null if nil, otherwise it is
359 // the recursively JSON-encoded representation of the underlying value.
360 // Format flags are forwarded to the encoding of the underlying value.
361 //
362 // - A Go interface is encoded as a JSON null if nil, otherwise it is
363 // the recursively JSON-encoded representation of the underlying value.
364 // It does not support any custom format flags.
365 //
366 // - A Go [time.Time] is encoded as a JSON string containing the timestamp
367 // formatted in RFC 3339 with nanosecond precision.
368 // If the format matches one of the format constants declared
369 // in the time package (e.g., RFC1123), then that format is used.
370 // If the format is "unix", "unixmilli", "unixmicro", or "unixnano",
371 // then the timestamp is encoded as a possibly fractional JSON number
372 // of the number of seconds (or milliseconds, microseconds, or nanoseconds)
373 // since the Unix epoch, which is January 1st, 1970 at 00:00:00 UTC.
374 // To avoid a fractional component, round the timestamp to the relevant unit.
375 // Otherwise, the format is used as-is with [time.Time.Format] if non-empty.
376 //
377 // - A Go [time.Duration] currently has no default representation and
378 // requires an explicit format to be specified.
379 // If the format is "sec", "milli", "micro", or "nano",
380 // then the duration is encoded as a possibly fractional JSON number
381 // of the number of seconds (or milliseconds, microseconds, or nanoseconds).
382 // To avoid a fractional component, round the duration to the relevant unit.
383 // If the format is "units", it is encoded as a JSON string formatted using
384 // [time.Duration.String] (e.g., "1h30m" for 1 hour 30 minutes).
385 // If the format is "iso8601", it is encoded as a JSON string using the
386 // ISO 8601 standard for durations (e.g., "PT1H30M" for 1 hour 30 minutes)
387 // using only accurate units of hours, minutes, and seconds.
388 //
389 // - All other Go types (e.g., complex numbers, channels, and functions)
390 // have no default representation and result in a [SemanticError].
391 //
392 // JSON cannot represent cyclic data structures and Marshal does not handle them.
393 // Passing cyclic structures will result in an error.
394 func Marshal(in any, opts ...Options) (out []byte, err error) {
395 return json.Marshal(in, opts...)
396 }
397
398 // MarshalWrite serializes a Go value into an [io.Writer] according to the provided
399 // marshal and encode options (while ignoring unmarshal or decode options).
400 // It does not terminate the output with a newline.
401 // See [Marshal] for details about the conversion of a Go value into JSON.
402 func MarshalWrite(out io.Writer, in any, opts ...Options) (err error) {
403 return json.MarshalWrite(out, in, opts...)
404 }
405
406 // MarshalEncode serializes a Go value into an [jsontext.Encoder] according to
407 // the provided marshal options (while ignoring unmarshal, encode, or decode options).
408 // Any marshal-relevant options already specified on the [jsontext.Encoder]
409 // take lower precedence than the set of options provided by the caller.
410 // Unlike [Marshal] and [MarshalWrite], encode options are ignored because
411 // they must have already been specified on the provided [jsontext.Encoder].
412 //
413 // See [Marshal] for details about the conversion of a Go value into JSON.
414 func MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) (err error) {
415 return json.MarshalEncode(out, in, opts...)
416 }
417
418 // Unmarshal decodes a []byte input into a Go value according to the provided
419 // unmarshal and decode options (while ignoring marshal or encode options).
420 // The input must be a single JSON value with optional whitespace interspersed.
421 // The output must be a non-nil pointer.
422 //
423 // Type-specific unmarshal functions and methods take precedence
424 // over the default representation of a value.
425 // Functions or methods that operate on *T are only called when decoding
426 // a value of type T (by taking its address) or a non-nil value of *T.
427 // Unmarshal ensures that a value is always addressable
428 // (by boxing it on the heap if necessary) so that
429 // these functions and methods can be consistently called.
430 //
431 // The input is decoded into the output according the following rules:
432 //
433 // - If any type-specific functions in a [WithUnmarshalers] option match
434 // the value type, then those functions are called to decode the JSON
435 // value. If all applicable functions return [errors.ErrUnsupported],
436 // then the input is decoded according to subsequent rules.
437 //
438 // - If the value type implements [UnmarshalerFrom],
439 // then the UnmarshalJSONFrom method is called to decode the JSON value.
440 // If the method returns [errors.ErrUnsupported],
441 // then the input is decoded according to subsequent rules.
442 //
443 // - If the value type implements [Unmarshaler],
444 // then the UnmarshalJSON method is called to decode the JSON value.
445 //
446 // - If the value type implements [encoding.TextUnmarshaler],
447 // then the input is decoded as a JSON string and
448 // the UnmarshalText method is called with the decoded string value.
449 // This fails with a [SemanticError] if the input is not a JSON string.
450 //
451 // - Otherwise, the JSON value is decoded according to the value's type
452 // as described in detail below.
453 //
454 // Most Go types have a default JSON representation.
455 // Certain types support specialized formatting according to
456 // a format flag optionally specified in the Go struct tag
457 // for the struct field that contains the current value
458 // (see the “JSON Representation of Go structs” section for more details).
459 // A JSON null may be decoded into every supported Go value where
460 // it is equivalent to storing the zero value of the Go value.
461 // If the input JSON kind is not handled by the current Go value type,
462 // then this fails with a [SemanticError]. Unless otherwise specified,
463 // the decoded value replaces any pre-existing value.
464 //
465 // The representation of each type is as follows:
466 //
467 // - A Go boolean is decoded from a JSON boolean (e.g., true or false).
468 // It does not support any custom format flags.
469 //
470 // - A Go string is decoded from a JSON string.
471 // It does not support any custom format flags.
472 //
473 // - A Go []byte or [N]byte is decoded from a JSON string
474 // containing the binary value encoded using RFC 4648.
475 // If the format is "base64" or unspecified, then this uses RFC 4648, section 4.
476 // If the format is "base64url", then this uses RFC 4648, section 5.
477 // If the format is "base32", then this uses RFC 4648, section 6.
478 // If the format is "base32hex", then this uses RFC 4648, section 7.
479 // If the format is "base16" or "hex", then this uses RFC 4648, section 8.
480 // If the format is "array", then the Go slice or array is decoded from a
481 // JSON array where each JSON element is recursively decoded for each byte.
482 // When decoding into a non-nil []byte, the slice length is reset to zero
483 // and the decoded input is appended to it.
484 // When decoding into a [N]byte, the input must decode to exactly N bytes,
485 // otherwise it fails with a [SemanticError].
486 //
487 // - A Go integer is decoded from a JSON number.
488 // It must be decoded from a JSON string containing a JSON number
489 // if [StringifyNumbers] is specified or decoding a JSON object name.
490 // It fails with a [SemanticError] if the JSON number
491 // has a fractional or exponent component.
492 // It also fails if it overflows the representation of the Go integer type.
493 // It does not support any custom format flags.
494 //
495 // - A Go float is decoded from a JSON number.
496 // It must be decoded from a JSON string containing a JSON number
497 // if [StringifyNumbers] is specified or decoding a JSON object name.
498 // It fails if it overflows the representation of the Go float type.
499 // If the format is "nonfinite", then the JSON strings
500 // "NaN", "Infinity", and "-Infinity" are decoded as NaN, +Inf, and -Inf.
501 // Otherwise, the presence of such strings results in a [SemanticError].
502 //
503 // - A Go map is decoded from a JSON object,
504 // where each JSON object name and value pair is recursively decoded
505 // as the Go map key and value. Maps are not cleared.
506 // If the Go map is nil, then a new map is allocated to decode into.
507 // If the decoded key matches an existing Go map entry, the entry value
508 // is reused by decoding the JSON object value into it.
509 // The formats "emitnull" and "emitempty" have no effect when decoding.
510 //
511 // - A Go struct is decoded from a JSON object.
512 // See the “JSON Representation of Go structs” section
513 // in the package-level documentation for more details.
514 //
515 // - A Go slice is decoded from a JSON array, where each JSON element
516 // is recursively decoded and appended to the Go slice.
517 // Before appending into a Go slice, a new slice is allocated if it is nil,
518 // otherwise the slice length is reset to zero.
519 // The formats "emitnull" and "emitempty" have no effect when decoding.
520 //
521 // - A Go array is decoded from a JSON array, where each JSON array element
522 // is recursively decoded as each corresponding Go array element.
523 // Each Go array element is zeroed before decoding into it.
524 // It fails with a [SemanticError] if the JSON array does not contain
525 // the exact same number of elements as the Go array.
526 // It does not support any custom format flags.
527 //
528 // - A Go pointer is decoded based on the JSON kind and underlying Go type.
529 // If the input is a JSON null, then this stores a nil pointer.
530 // Otherwise, it allocates a new underlying value if the pointer is nil,
531 // and recursively JSON decodes into the underlying value.
532 // Format flags are forwarded to the decoding of the underlying type.
533 //
534 // - A Go interface is decoded based on the JSON kind and underlying Go type.
535 // If the input is a JSON null, then this stores a nil interface value.
536 // Otherwise, a nil interface value of an empty interface type is initialized
537 // with a zero Go bool, string, float64, map[string]any, or []any if the
538 // input is a JSON boolean, string, number, object, or array, respectively.
539 // If the interface value is still nil, then this fails with a [SemanticError]
540 // since decoding could not determine an appropriate Go type to decode into.
541 // For example, unmarshaling into a nil io.Reader fails since
542 // there is no concrete type to populate the interface value with.
543 // Otherwise an underlying value exists and it recursively decodes
544 // the JSON input into it. It does not support any custom format flags.
545 //
546 // - A Go [time.Time] is decoded from a JSON string containing the time
547 // formatted in RFC 3339 with nanosecond precision.
548 // If the format matches one of the format constants declared in
549 // the time package (e.g., RFC1123), then that format is used for parsing.
550 // If the format is "unix", "unixmilli", "unixmicro", or "unixnano",
551 // then the timestamp is decoded from an optionally fractional JSON number
552 // of the number of seconds (or milliseconds, microseconds, or nanoseconds)
553 // since the Unix epoch, which is January 1st, 1970 at 00:00:00 UTC.
554 // Otherwise, the format is used as-is with [time.Time.Parse] if non-empty.
555 //
556 // - A Go [time.Duration] currently has no default representation and
557 // requires an explicit format to be specified.
558 // If the format is "sec", "milli", "micro", or "nano",
559 // then the duration is decoded from an optionally fractional JSON number
560 // of the number of seconds (or milliseconds, microseconds, or nanoseconds).
561 // If the format is "units", it is decoded from a JSON string parsed using
562 // [time.ParseDuration] (e.g., "1h30m" for 1 hour 30 minutes).
563 // If the format is "iso8601", it is decoded from a JSON string using the
564 // ISO 8601 standard for durations (e.g., "PT1H30M" for 1 hour 30 minutes)
565 // accepting only accurate units of hours, minutes, or seconds.
566 //
567 // - All other Go types (e.g., complex numbers, channels, and functions)
568 // have no default representation and result in a [SemanticError].
569 //
570 // In general, unmarshaling follows merge semantics (similar to RFC 7396)
571 // where the decoded Go value replaces the destination value
572 // for any JSON kind other than an object.
573 // For JSON objects, the input object is merged into the destination value
574 // where matching object members recursively apply merge semantics.
575 func Unmarshal(in []byte, out any, opts ...Options) (err error) {
576 return json.Unmarshal(in, out, opts...)
577 }
578
579 // UnmarshalRead deserializes a Go value from an [io.Reader] according to the
580 // provided unmarshal and decode options (while ignoring marshal or encode options).
581 // The input must be a single JSON value with optional whitespace interspersed.
582 // It consumes the entirety of [io.Reader] until [io.EOF] is encountered,
583 // without reporting an error for EOF. The output must be a non-nil pointer.
584 // See [Unmarshal] for details about the conversion of JSON into a Go value.
585 func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error) {
586 return json.UnmarshalRead(in, out, opts...)
587 }
588
589 // UnmarshalDecode deserializes a Go value from a [jsontext.Decoder] according to
590 // the provided unmarshal options (while ignoring marshal, encode, or decode options).
591 // Any unmarshal options already specified on the [jsontext.Decoder]
592 // take lower precedence than the set of options provided by the caller.
593 // Unlike [Unmarshal] and [UnmarshalRead], decode options are ignored because
594 // they must have already been specified on the provided [jsontext.Decoder].
595 //
596 // The input may be a stream of zero or more JSON values,
597 // where this only unmarshals the next JSON value in the stream.
598 // If there are no more top-level JSON values, it reports [io.EOF].
599 // The output must be a non-nil pointer.
600 // See [Unmarshal] for details about the conversion of JSON into a Go value.
601 func UnmarshalDecode(in *jsontext.Decoder, out any, opts ...Options) (err error) {
602 return json.UnmarshalDecode(in, out, opts...)
603 }
604
605 // Marshalers is a list of functions that may override the marshal behavior
606 // of specific types. Populate [WithMarshalers] to use it with
607 // [Marshal], [MarshalWrite], or [MarshalEncode].
608 // A nil *Marshalers is equivalent to an empty list.
609 // There are no exported fields or methods on Marshalers.
610 type Marshalers = json.Marshalers
611
612 // JoinMarshalers constructs a flattened list of marshal functions.
613 // If multiple functions in the list are applicable for a value of a given type,
614 // then those earlier in the list take precedence over those that come later.
615 // If a function returns [errors.ErrUnsupported],
616 // then the next applicable function is called,
617 // otherwise the default marshaling behavior is used.
618 //
619 // For example:
620 //
621 // m1 := JoinMarshalers(f1, f2)
622 // m2 := JoinMarshalers(f0, m1, f3) // equivalent to m3
623 // m3 := JoinMarshalers(f0, f1, f2, f3) // equivalent to m2
624 func JoinMarshalers(ms ...*Marshalers) *Marshalers {
625 return json.JoinMarshalers(ms...)
626 }
627
628 // Unmarshalers is a list of functions that may override the unmarshal behavior
629 // of specific types. Populate [WithUnmarshalers] to use it with
630 // [Unmarshal], [UnmarshalRead], or [UnmarshalDecode].
631 // A nil *Unmarshalers is equivalent to an empty list.
632 // There are no exported fields or methods on Unmarshalers.
633 type Unmarshalers = json.Unmarshalers
634
635 // JoinUnmarshalers constructs a flattened list of unmarshal functions.
636 // If multiple functions in the list are applicable for a value of a given type,
637 // then those earlier in the list take precedence over those that come later.
638 // If a function returns [errors.ErrUnsupported],
639 // then the next applicable function is called,
640 // otherwise the default unmarshaling behavior is used.
641 //
642 // For example:
643 //
644 // u1 := JoinUnmarshalers(f1, f2)
645 // u2 := JoinUnmarshalers(f0, u1, f3) // equivalent to u3
646 // u3 := JoinUnmarshalers(f0, f1, f2, f3) // equivalent to u2
647 func JoinUnmarshalers(us ...*Unmarshalers) *Unmarshalers {
648 return json.JoinUnmarshalers(us...)
649 }
650
651 // MarshalFunc constructs a type-specific marshaler that
652 // specifies how to marshal values of type T.
653 // T can be any type except a named pointer.
654 // The function is always provided with a non-nil pointer value
655 // if T is an interface or pointer type.
656 //
657 // The function must marshal exactly one JSON value.
658 // The value of T must not be retained outside the function call.
659 // It may not return [errors.ErrUnsupported].
660 func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers {
661 return json.MarshalFunc[T](fn)
662 }
663
664 // MarshalToFunc constructs a type-specific marshaler that
665 // specifies how to marshal values of type T.
666 // T can be any type except a named pointer.
667 // The function is always provided with a non-nil pointer value
668 // if T is an interface or pointer type.
669 //
670 // The function must marshal exactly one JSON value by calling write methods
671 // on the provided encoder. It may return [errors.ErrUnsupported] such that marshaling can
672 // move on to the next marshal function. However, no mutable method calls may
673 // be called on the encoder if [errors.ErrUnsupported] is returned.
674 // The pointer to [jsontext.Encoder] and the value of T
675 // must not be retained outside the function call.
676 func MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers {
677 return json.MarshalToFunc[T](fn)
678 }
679
680 // UnmarshalFunc constructs a type-specific unmarshaler that
681 // specifies how to unmarshal values of type T.
682 // T must be an unnamed pointer or an interface type.
683 // The function is always provided with a non-nil pointer value.
684 //
685 // The function must unmarshal exactly one JSON value.
686 // The input []byte must not be mutated.
687 // The input []byte and value T must not be retained outside the function call.
688 // It may not return [errors.ErrUnsupported].
689 func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers {
690 return json.UnmarshalFunc[T](fn)
691 }
692
693 // UnmarshalFromFunc constructs a type-specific unmarshaler that
694 // specifies how to unmarshal values of type T.
695 // T must be an unnamed pointer or an interface type.
696 // The function is always provided with a non-nil pointer value.
697 //
698 // The function must unmarshal exactly one JSON value by calling read methods
699 // on the provided decoder. It may return [errors.ErrUnsupported] such that unmarshaling can
700 // move on to the next unmarshal function. However, no mutable method calls may
701 // be called on the decoder if [errors.ErrUnsupported] is returned.
702 // The pointer to [jsontext.Decoder] and the value of T
703 // must not be retained outside the function call.
704 func UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers {
705 return json.UnmarshalFromFunc[T](fn)
706 }
707
708 // Marshaler is implemented by types that can marshal themselves.
709 // It is recommended that types implement [MarshalerTo] unless the implementation
710 // is trying to avoid a hard dependency on the "jsontext" package.
711 //
712 // It is recommended that implementations return a buffer that is safe
713 // for the caller to retain and potentially mutate.
714 //
715 // If the returned error is a [SemanticError], then unpopulated fields
716 // of the error may be populated by [json] with additional context.
717 // Errors of other types are wrapped within a [SemanticError].
718 type Marshaler = json.Marshaler
719
720 // MarshalerTo is implemented by types that can marshal themselves.
721 // It is recommended that types implement MarshalerTo instead of [Marshaler]
722 // since this is both more performant and flexible.
723 // If a type implements both Marshaler and MarshalerTo,
724 // then MarshalerTo takes precedence. In such a case, both implementations
725 // should aim to have equivalent behavior for the default marshal options.
726 //
727 // The implementation must write only one JSON value to the Encoder.
728 // Alternatively, it may return [errors.ErrUnsupported] without mutating
729 // the Encoder. The "json" package calling the method will
730 // use the next available JSON representation for the receiver type.
731 // Implementations must not retain the pointer to [jsontext.Encoder].
732 //
733 // If the returned error is a [SemanticError], then unpopulated fields
734 // of the error may be populated by [json] with additional context.
735 // Errors of other types are wrapped within a [SemanticError],
736 // unless it is an IO error.
737 //
738 // The MarshalJSONTo method should not be directly called as it may
739 // return sentinel errors that need special handling.
740 // Users should instead call [MarshalEncode], which handles such cases.
741 type MarshalerTo = json.MarshalerTo
742
743 // Unmarshaler is implemented by types that can unmarshal themselves.
744 // It is recommended that types implement [UnmarshalerFrom] unless the implementation
745 // is trying to avoid a hard dependency on the "jsontext" package.
746 //
747 // The input can be assumed to be a valid encoding of a JSON value
748 // if called from unmarshal functionality in this package.
749 // UnmarshalJSON must copy the JSON data if it is retained after returning.
750 // It is recommended that UnmarshalJSON implement merge semantics when
751 // unmarshaling into a pre-populated value.
752 //
753 // Implementations must not retain or mutate the input []byte.
754 //
755 // If the returned error is a [SemanticError], then unpopulated fields
756 // of the error may be populated by [json] with additional context.
757 // Errors of other types are wrapped within a [SemanticError].
758 type Unmarshaler = json.Unmarshaler
759
760 // UnmarshalerFrom is implemented by types that can unmarshal themselves.
761 // It is recommended that types implement UnmarshalerFrom instead of [Unmarshaler]
762 // since this is both more performant and flexible.
763 // If a type implements both Unmarshaler and UnmarshalerFrom,
764 // then UnmarshalerFrom takes precedence. In such a case, both implementations
765 // should aim to have equivalent behavior for the default unmarshal options.
766 //
767 // The implementation must read only one JSON value from the Decoder.
768 // It is recommended that UnmarshalJSONFrom implement merge semantics when
769 // unmarshaling into a pre-populated value.
770 // Alternatively, it may return [errors.ErrUnsupported] without mutating
771 // the Decoder. The "json" package calling the method will
772 // use the next available JSON representation for the receiver type.
773 // Implementations must not retain the pointer to [jsontext.Decoder].
774 //
775 // If the returned error is a [SemanticError], then unpopulated fields
776 // of the error may be populated by [json] with additional context.
777 // Errors of other types are wrapped within a [SemanticError],
778 // unless it is a [jsontext.SyntacticError] or an IO error.
779 //
780 // The UnmarshalJSONFrom method should not be directly called as it may
781 // return sentinel errors that need special handling.
782 // Users should instead call [UnmarshalDecode], which handles such cases.
783 type UnmarshalerFrom = json.UnmarshalerFrom
784
785 // ErrUnknownName indicates that a JSON object member could not be
786 // unmarshaled because the name is not known to the target Go struct.
787 // This error is directly wrapped within a [SemanticError] when produced.
788 //
789 // The name of an unknown JSON object member can be extracted as:
790 //
791 // err := ...
792 // serr, ok := errors.AsType[*json.SemanticError](err)
793 // if ok && serr.Err == json.ErrUnknownName {
794 // ptr := serr.JSONPointer // JSON pointer to unknown name
795 // name := ptr.LastToken() // unknown name itself
796 // ...
797 // }
798 //
799 // This error is only returned if [RejectUnknownMembers] is true.
800 var ErrUnknownName = json.ErrUnknownName
801
802 // SemanticError describes an error determining the meaning
803 // of JSON data as Go data or vice-versa.
804 //
805 // If a [Marshaler], [MarshalerTo], [Unmarshaler], or [UnmarshalerFrom] method
806 // returns a SemanticError when called by the [json] package,
807 // then the ByteOffset, JSONPointer, and GoType fields are automatically
808 // populated by the calling context if they are the zero value.
809 //
810 // The contents of this error as produced by this package may change over time.
811 type SemanticError = json.SemanticError
812
813 // Options configure [Marshal], [MarshalWrite], [MarshalEncode],
814 // [Unmarshal], [UnmarshalRead], and [UnmarshalDecode] with specific features.
815 // Each function takes in a variadic list of options, where properties
816 // set in later options override the value of previously set properties.
817 //
818 // The Options type is identical to [encoding/json.Options] and
819 // [encoding/json/jsontext.Options]. Options from the other packages can
820 // be used interchangeably with functionality in this package.
821 //
822 // Options represent either a singular option or a set of options.
823 // It can be functionally thought of as a Go map of option properties
824 // (even though the underlying implementation avoids Go maps for performance).
825 //
826 // The constructors (e.g., [Deterministic]) return a singular option value:
827 //
828 // opt := Deterministic(true)
829 //
830 // which is analogous to creating a single entry map:
831 //
832 // opt := Options{"Deterministic": true}
833 //
834 // [JoinOptions] composes multiple options values to together:
835 //
836 // out := JoinOptions(opts...)
837 //
838 // which is analogous to making a new map and copying the options over:
839 //
840 // out := make(Options)
841 // for _, m := range opts {
842 // for k, v := range m {
843 // out[k] = v
844 // }
845 // }
846 //
847 // [GetOption] looks up the value of options parameter:
848 //
849 // v, ok := GetOption(opts, Deterministic)
850 //
851 // which is analogous to a Go map lookup:
852 //
853 // v, ok := Options["Deterministic"]
854 //
855 // There is a single Options type, which is used with both marshal and unmarshal.
856 // Some options affect both operations, while others only affect one operation:
857 //
858 // - [StringifyNumbers] affects marshaling and unmarshaling
859 // - [Deterministic] affects marshaling only
860 // - [FormatNilSliceAsNull] affects marshaling only
861 // - [FormatNilMapAsNull] affects marshaling only
862 // - [OmitZeroStructFields] affects marshaling only
863 // - [MatchCaseInsensitiveNames] affects marshaling and unmarshaling
864 // - [RejectUnknownMembers] affects unmarshaling only
865 // - [WithMarshalers] affects marshaling only
866 // - [WithUnmarshalers] affects unmarshaling only
867 //
868 // Options that do not affect a particular operation are ignored.
869 type Options = json.Options
870
871 // JoinOptions coalesces the provided list of options into a single Options.
872 // Properties set in later options override the value of previously set properties.
873 func JoinOptions(srcs ...Options) Options {
874 return json.JoinOptions(srcs...)
875 }
876
877 // GetOption returns the value stored in opts with the provided setter,
878 // reporting whether the value is present.
879 //
880 // Example usage:
881 //
882 // v, ok := json.GetOption(opts, json.Deterministic)
883 //
884 // Options are most commonly introspected to alter the JSON representation of
885 // [MarshalerTo.MarshalJSONTo] and [UnmarshalerFrom.UnmarshalJSONFrom] methods, and
886 // [MarshalToFunc] and [UnmarshalFromFunc] functions.
887 // In such cases, the presence bit should generally be ignored.
888 func GetOption[T any](opts Options, setter func(T) Options) (T, bool) {
889 return json.GetOption[T](opts, setter)
890 }
891
892 // DefaultOptionsV2 is the full set of all options that define v2 semantics.
893 // It is equivalent to the set of options in [encoding/json.DefaultOptionsV1]
894 // all being set to false. All other options are not present.
895 func DefaultOptionsV2() Options {
896 return json.DefaultOptionsV2()
897 }
898
899 // StringifyNumbers specifies that numeric Go types should be marshaled
900 // as a JSON string containing the equivalent JSON number value.
901 // When unmarshaling, numeric Go types are parsed from a JSON string
902 // containing the JSON number without any surrounding whitespace.
903 //
904 // According to RFC 8259, section 6, a JSON implementation may choose to
905 // limit the representation of a JSON number to an IEEE 754 binary64 value.
906 // This may cause decoders to lose precision for int64 and uint64 types.
907 // Quoting JSON numbers as a JSON string preserves the exact precision.
908 //
909 // This affects either marshaling or unmarshaling.
910 func StringifyNumbers(v bool) Options {
911 return json.StringifyNumbers(v)
912 }
913
914 // Deterministic specifies that the same input value will be serialized
915 // as the exact same output bytes. Different processes of
916 // the same program will serialize equal values to the same bytes,
917 // but different versions of the same program are not guaranteed
918 // to produce the exact same sequence of bytes.
919 //
920 // This only affects marshaling and is ignored when unmarshaling.
921 func Deterministic(v bool) Options {
922 return json.Deterministic(v)
923 }
924
925 // FormatNilSliceAsNull specifies that a nil Go slice should marshal as a
926 // JSON null instead of the default representation as an empty JSON array
927 // (or an empty JSON string in the case of ~[]byte).
928 // Slice fields explicitly marked with `format:emitempty` still marshal
929 // as an empty JSON array.
930 //
931 // This only affects marshaling and is ignored when unmarshaling.
932 func FormatNilSliceAsNull(v bool) Options {
933 return json.FormatNilSliceAsNull(v)
934 }
935
936 // FormatNilMapAsNull specifies that a nil Go map should marshal as a
937 // JSON null instead of the default representation as an empty JSON object.
938 // Map fields explicitly marked with `format:emitempty` still marshal
939 // as an empty JSON object.
940 //
941 // This only affects marshaling and is ignored when unmarshaling.
942 func FormatNilMapAsNull(v bool) Options {
943 return json.FormatNilMapAsNull(v)
944 }
945
946 // OmitZeroStructFields specifies that a Go struct should marshal in such a way
947 // that all struct fields that are zero are omitted from the marshaled output
948 // if the value is zero as determined by the "IsZero() bool" method if present,
949 // otherwise based on whether the field is the zero Go value.
950 // This is semantically equivalent to specifying the `omitzero` tag option
951 // on every field in a Go struct.
952 //
953 // This only affects marshaling and is ignored when unmarshaling.
954 func OmitZeroStructFields(v bool) Options {
955 return json.OmitZeroStructFields(v)
956 }
957
958 // MatchCaseInsensitiveNames specifies that JSON object members are matched
959 // against Go struct fields using a case-insensitive match of the name.
960 // Go struct fields explicitly marked with `case:strict` or `case:ignore`
961 // always use case-sensitive (or case-insensitive) name matching,
962 // regardless of the value of this option.
963 //
964 // This affects either marshaling or unmarshaling.
965 // For marshaling, this option may alter the detection of duplicate names
966 // (assuming [jsontext.AllowDuplicateNames] is false) from inlined fields
967 // if it matches one of the declared fields in the Go struct.
968 func MatchCaseInsensitiveNames(v bool) Options {
969 return json.MatchCaseInsensitiveNames(v)
970 }
971
972 // RejectUnknownMembers specifies that unknown members should be rejected
973 // when unmarshaling a JSON object.
974 //
975 // This only affects unmarshaling and is ignored when marshaling.
976 func RejectUnknownMembers(v bool) Options {
977 return json.RejectUnknownMembers(v)
978 }
979
980 // WithMarshalers specifies a list of type-specific marshalers to use,
981 // which can be used to override the default marshal behavior for values
982 // of particular types.
983 //
984 // This only affects marshaling and is ignored when unmarshaling.
985 func WithMarshalers(v *Marshalers) Options {
986 return json.WithMarshalers(v)
987 }
988
989 // WithUnmarshalers specifies a list of type-specific unmarshalers to use,
990 // which can be used to override the default unmarshal behavior for values
991 // of particular types.
992 //
993 // This only affects unmarshaling and is ignored when marshaling.
994 func WithUnmarshalers(v *Unmarshalers) Options {
995 return json.WithUnmarshalers(v)
996 }