| 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 encoding and decoding of JSON as defined in |
| 10 | // RFC 7159. The mapping between JSON and Go values is described |
| 11 | // in the documentation for the Marshal and Unmarshal functions. |
| 12 | // |
| 13 | // See "JSON and Go" for an introduction to this package: |
| 14 | // https://golang.org/doc/articles/json_and_go.html |
| 15 | // |
| 16 | // # Security Considerations |
| 17 | // |
| 18 | // See the "Security Considerations" section in [encoding/json/v2]. |
| 19 | // |
| 20 | // For historical reasons, the default behavior of v1 [encoding/json] |
| 21 | // unfortunately operates with less secure defaults. |
| 22 | // New usages of JSON in Go are encouraged to use [encoding/json/v2] instead. |
| 23 | // Migrating to v2 |
| 24 | // |
| 25 | // This package (i.e., [encoding/json]) is now formally known as the v1 package |
| 26 | // since a v2 package now exists at [encoding/json/v2]. |
| 27 | // All the behavior of the v1 package is implemented in terms of |
| 28 | // the v2 package with the appropriate set of options specified that |
| 29 | // preserve the historical behavior of v1. |
| 30 | // |
| 31 | // The [jsonv2.Marshal] function is the newer equivalent of v1 [Marshal]. |
| 32 | // The [jsonv2.Unmarshal] function is the newer equivalent of v1 [Unmarshal]. |
| 33 | // The v2 functions have the same calling signature as the v1 equivalent |
| 34 | // except that they take in variadic [Options] arguments that can be specified |
| 35 | // to alter the behavior of marshal or unmarshal. Both v1 and v2 generally |
| 36 | // behave in similar ways, but there are some notable differences. |
| 37 | // |
| 38 | // The following is a list of differences between v1 and v2: |
| 39 | // |
| 40 | // - In v1, JSON object members are unmarshaled into a Go struct using a |
| 41 | // case-insensitive name match with the JSON name of the fields. |
| 42 | // In contrast, v2 matches fields using an exact, case-sensitive match. |
| 43 | // The [jsonv2.MatchCaseInsensitiveNames] and [MatchCaseSensitiveDelimiter] |
| 44 | // options control this behavior difference. To explicitly specify a Go struct |
| 45 | // field to use a particular name matching scheme, either the `case:ignore` |
| 46 | // or the `case:strict` field option can be specified. |
| 47 | // Field-specified options take precedence over caller-specified options. |
| 48 | // |
| 49 | // - In v1, when marshaling a Go struct, a field marked as `omitempty` |
| 50 | // is omitted if the field value is an "empty" Go value, which is defined as |
| 51 | // false, 0, a nil pointer, a nil interface value, and |
| 52 | // any empty array, slice, map, or string. In contrast, v2 redefines |
| 53 | // `omitempty` to omit a field if it encodes as an "empty" JSON value, |
| 54 | // which is defined as a JSON null, or an empty JSON string, object, or array. |
| 55 | // The [OmitEmptyWithLegacySemantics] option controls this behavior difference. |
| 56 | // Note that `omitempty` behaves identically in both v1 and v2 for a |
| 57 | // Go array, slice, map, or string (assuming no user-defined MarshalJSON method |
| 58 | // overrides the default representation). Existing usages of `omitempty` on a |
| 59 | // Go bool, number, pointer, or interface value should migrate to specifying |
| 60 | // `omitzero` instead (which is identically supported in both v1 and v2). |
| 61 | // |
| 62 | // - In v1, a Go struct field marked as `string` can be used to quote a |
| 63 | // Go string, bool, or number as a JSON string. It does not recursively |
| 64 | // take effect on composite Go types. In contrast, v2 restricts |
| 65 | // the `string` option to only quote a Go number as a JSON string. |
| 66 | // It does recursively take effect on Go numbers within a composite Go type. |
| 67 | // The [StringifyWithLegacySemantics] option controls this behavior difference. |
| 68 | // |
| 69 | // - In v1, a nil Go slice or Go map is marshaled as a JSON null. |
| 70 | // In contrast, v2 marshals a nil Go slice or Go map as |
| 71 | // an empty JSON array or JSON object, respectively. |
| 72 | // The [jsonv2.FormatNilSliceAsNull] and [jsonv2.FormatNilMapAsNull] options |
| 73 | // control this behavior difference. To explicitly specify a Go struct field |
| 74 | // to use a particular representation for nil, either the `format:emitempty` |
| 75 | // or `format:emitnull` field option can be specified. |
| 76 | // Field-specified options take precedence over caller-specified options. |
| 77 | // |
| 78 | // - In v1, a Go array may be unmarshaled from a JSON array of any length. |
| 79 | // In contrast, in v2 a Go array must be unmarshaled from a JSON array |
| 80 | // of the same length, otherwise it results in an error. |
| 81 | // The [UnmarshalArrayFromAnyLength] option controls this behavior difference. |
| 82 | // |
| 83 | // - In v1, a Go byte array is represented as a JSON array of JSON numbers. |
| 84 | // In contrast, in v2 a Go byte array is represented as a Base64-encoded JSON string. |
| 85 | // The [FormatByteArrayAsArray] option controls this behavior difference. |
| 86 | // To explicitly specify a Go struct field to use a particular representation, |
| 87 | // either the `format:array` or `format:base64` field option can be specified. |
| 88 | // Field-specified options take precedence over caller-specified options. |
| 89 | // |
| 90 | // - In v1, MarshalJSON methods declared on a pointer receiver are only called |
| 91 | // if the Go value is addressable. In contrast, in v2 a MarshalJSON method |
| 92 | // is always callable regardless of addressability. |
| 93 | // The [CallMethodsWithLegacySemantics] option controls this behavior difference. |
| 94 | // |
| 95 | // - In v1, MarshalJSON and UnmarshalJSON methods are never called for Go map keys. |
| 96 | // In contrast, in v2 a MarshalJSON or UnmarshalJSON method is eligible for |
| 97 | // being called for Go map keys. |
| 98 | // The [CallMethodsWithLegacySemantics] option controls this behavior difference. |
| 99 | // |
| 100 | // - In v1, a Go map is marshaled in a deterministic order. |
| 101 | // In contrast, in v2 a Go map is marshaled in a non-deterministic order. |
| 102 | // The [jsonv2.Deterministic] option controls this behavior difference. |
| 103 | // |
| 104 | // - In v1, JSON strings are encoded with HTML-specific or JavaScript-specific |
| 105 | // characters being escaped. In contrast, in v2 JSON strings use the minimal |
| 106 | // encoding and only escape if required by the JSON grammar. |
| 107 | // The [jsontext.EscapeForHTML] and [jsontext.EscapeForJS] options |
| 108 | // control this behavior difference. |
| 109 | // |
| 110 | // - In v1, bytes of invalid UTF-8 within a string are silently replaced with |
| 111 | // the Unicode replacement character. In contrast, in v2 the presence of |
| 112 | // invalid UTF-8 results in an error. The [jsontext.AllowInvalidUTF8] option |
| 113 | // controls this behavior difference. |
| 114 | // |
| 115 | // - In v1, a JSON object with duplicate names is permitted. |
| 116 | // In contrast, in v2 a JSON object with duplicate names results in an error. |
| 117 | // The [jsontext.AllowDuplicateNames] option controls this behavior difference. |
| 118 | // |
| 119 | // - In v1, when unmarshaling a JSON null into a non-empty Go value it will |
| 120 | // inconsistently either zero out the value or do nothing. |
| 121 | // In contrast, in v2 unmarshaling a JSON null will consistently and always |
| 122 | // zero out the underlying Go value. The [MergeWithLegacySemantics] option |
| 123 | // controls this behavior difference. |
| 124 | // |
| 125 | // - In v1, when unmarshaling a JSON value into a non-zero Go value, |
| 126 | // it merges into the original Go value for array elements, slice elements, |
| 127 | // struct fields (but not map values), |
| 128 | // pointer values, and interface values (only if a non-nil pointer). |
| 129 | // In contrast, in v2 unmarshal merges into the Go value |
| 130 | // for struct fields, map values, pointer values, and interface values. |
| 131 | // In general, the v2 semantic merges when unmarshaling a JSON object, |
| 132 | // otherwise it replaces the value. The [MergeWithLegacySemantics] option |
| 133 | // controls this behavior difference. |
| 134 | // |
| 135 | // - In v1, a [time.Duration] is represented as a JSON number containing |
| 136 | // the decimal number of nanoseconds. In contrast, in v2 a [time.Duration] |
| 137 | // has no default representation and results in a runtime error. |
| 138 | // The [FormatDurationAsNano] option controls this behavior difference. |
| 139 | // To explicitly specify a Go struct field to use a particular representation, |
| 140 | // either the `format:nano` or `format:units` field option can be specified. |
| 141 | // Field-specified options take precedence over caller-specified options. |
| 142 | // |
| 143 | // - In v1, errors are never reported at runtime for Go struct types |
| 144 | // that have some form of structural error (e.g., a malformed tag option). |
| 145 | // In contrast, v2 reports a runtime error for Go types that are invalid |
| 146 | // as they relate to JSON serialization. For example, a Go struct |
| 147 | // with only unexported fields cannot be serialized. |
| 148 | // The [ReportErrorsWithLegacySemantics] option controls this behavior difference. |
| 149 | // |
| 150 | // As mentioned, the entirety of v1 is implemented in terms of v2, |
| 151 | // where options are implicitly specified to opt into legacy behavior. |
| 152 | // For example, [Marshal] directly calls [jsonv2.Marshal] with [DefaultOptionsV1]. |
| 153 | // Similarly, [Unmarshal] directly calls [jsonv2.Unmarshal] with [DefaultOptionsV1]. |
| 154 | // The [DefaultOptionsV1] option represents the set of all options that specify |
| 155 | // default v1 behavior. |
| 156 | // |
| 157 | // For many of the behavior differences, there are Go struct field options |
| 158 | // that the author of a Go type can specify to control the behavior such that |
| 159 | // the type is represented identically in JSON under either v1 or v2 semantics. |
| 160 | // |
| 161 | // The availability of [DefaultOptionsV1] and [jsonv2.DefaultOptionsV2], |
| 162 | // where later options take precedence over former options allows for |
| 163 | // a gradual migration from v1 to v2. For example: |
| 164 | // |
| 165 | // - jsonv1.Marshal(v) |
| 166 | // uses default v1 semantics. |
| 167 | // |
| 168 | // - jsonv2.Marshal(v, jsonv1.DefaultOptionsV1()) |
| 169 | // is semantically equivalent to jsonv1.Marshal |
| 170 | // and thus uses default v1 semantics. |
| 171 | // |
| 172 | // - jsonv2.Marshal(v, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false)) |
| 173 | // uses mostly v1 semantics, but opts into one particular v2-specific behavior. |
| 174 | // |
| 175 | // - jsonv2.Marshal(v, jsonv1.CallMethodsWithLegacySemantics(true)) |
| 176 | // uses mostly v2 semantics, but opts into one particular v1-specific behavior. |
| 177 | // |
| 178 | // - jsonv2.Marshal(v, ..., jsonv2.DefaultOptionsV2()) |
| 179 | // is semantically equivalent to jsonv2.Marshal since |
| 180 | // jsonv2.DefaultOptionsV2 overrides any options specified earlier |
| 181 | // and thus uses default v2 semantics. |
| 182 | // |
| 183 | // - jsonv2.Marshal(v) |
| 184 | // uses default v2 semantics. |
| 185 | // |
| 186 | // All new usages of "json" in Go should use the v2 package, |
| 187 | // but the v1 package will forever remain supported. |
| 188 | package json |
| 189 | |
| 190 | import ( |
| 191 | "bytes" |
| 192 | "encoding/json" |
| 193 | "io" |
| 194 | ) |
| 195 | |
| 196 | // Unmarshal parses the JSON-encoded data and stores the result |
| 197 | // in the value pointed to by v. If v is nil or not a pointer, |
| 198 | // Unmarshal returns an [InvalidUnmarshalError]. |
| 199 | // |
| 200 | // Unmarshal uses the inverse of the encodings that |
| 201 | // [Marshal] uses, allocating maps, slices, and pointers as necessary, |
| 202 | // with the following additional rules: |
| 203 | // |
| 204 | // To unmarshal JSON into a pointer, Unmarshal first handles the case of |
| 205 | // the JSON being the JSON literal null. In that case, Unmarshal sets |
| 206 | // the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into |
| 207 | // the value pointed at by the pointer. If the pointer is nil, Unmarshal |
| 208 | // allocates a new value for it to point to. |
| 209 | // |
| 210 | // To unmarshal JSON into a value implementing [Unmarshaler], |
| 211 | // Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including |
| 212 | // when the input is a JSON null. |
| 213 | // Otherwise, if the value implements [encoding.TextUnmarshaler] |
| 214 | // and the input is a JSON quoted string, Unmarshal calls |
| 215 | // [encoding.TextUnmarshaler.UnmarshalText] with the unquoted form of the string. |
| 216 | // |
| 217 | // To unmarshal JSON into a struct, Unmarshal matches incoming object |
| 218 | // keys to the keys used by [Marshal] (either the struct field name or its tag), |
| 219 | // preferring an exact match but also accepting a case-insensitive match. By |
| 220 | // default, object keys which don't have a corresponding struct field are |
| 221 | // ignored (see [Decoder.DisallowUnknownFields] for an alternative). |
| 222 | // |
| 223 | // To unmarshal JSON into an interface value, |
| 224 | // Unmarshal stores one of these in the interface value: |
| 225 | // |
| 226 | // - bool, for JSON booleans |
| 227 | // - float64, for JSON numbers |
| 228 | // - string, for JSON strings |
| 229 | // - []any, for JSON arrays |
| 230 | // - map[string]any, for JSON objects |
| 231 | // - nil for JSON null |
| 232 | // |
| 233 | // To unmarshal a JSON array into a slice, Unmarshal resets the slice length |
| 234 | // to zero and then appends each element to the slice. |
| 235 | // As a special case, to unmarshal an empty JSON array into a slice, |
| 236 | // Unmarshal replaces the slice with a new empty slice. |
| 237 | // |
| 238 | // To unmarshal a JSON array into a Go array, Unmarshal decodes |
| 239 | // JSON array elements into corresponding Go array elements. |
| 240 | // If the Go array is smaller than the JSON array, |
| 241 | // the additional JSON array elements are discarded. |
| 242 | // If the JSON array is smaller than the Go array, |
| 243 | // the additional Go array elements are set to zero values. |
| 244 | // |
| 245 | // To unmarshal a JSON object into a map, Unmarshal first establishes a map to |
| 246 | // use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal |
| 247 | // reuses the existing map, keeping existing entries. Unmarshal then stores |
| 248 | // key-value pairs from the JSON object into the map. The map's key type must |
| 249 | // either be any string type, an integer, or implement [encoding.TextUnmarshaler]. |
| 250 | // |
| 251 | // If the JSON-encoded data contain a syntax error, Unmarshal returns a [SyntaxError]. |
| 252 | // |
| 253 | // If a JSON value is not appropriate for a given target type, |
| 254 | // or if a JSON number overflows the target type, Unmarshal |
| 255 | // skips that field and completes the unmarshaling as best it can. |
| 256 | // If no more serious errors are encountered, Unmarshal returns |
| 257 | // an [UnmarshalTypeError] describing the earliest such error. In any |
| 258 | // case, it's not guaranteed that all the remaining fields following |
| 259 | // the problematic one will be unmarshaled into the target object. |
| 260 | // |
| 261 | // The JSON null value unmarshals into an interface, map, pointer, or slice |
| 262 | // by setting that Go value to nil. Because null is often used in JSON to mean |
| 263 | // “not present,” unmarshaling a JSON null into any other Go type has no effect |
| 264 | // on the value and produces no error. |
| 265 | // |
| 266 | // When unmarshaling quoted strings, invalid UTF-8 or |
| 267 | // invalid UTF-16 surrogate pairs are not treated as an error. |
| 268 | // Instead, they are replaced by the Unicode replacement |
| 269 | // character U+FFFD. |
| 270 | func Unmarshal(data []byte, v any) error { |
| 271 | return json.Unmarshal(data, v) |
| 272 | } |
| 273 | |
| 274 | // Unmarshaler is the interface implemented by types |
| 275 | // that can unmarshal a JSON description of themselves. |
| 276 | // The input can be assumed to be a valid encoding of |
| 277 | // a JSON value. UnmarshalJSON must copy the JSON data |
| 278 | // if it wishes to retain the data after returning. |
| 279 | type Unmarshaler = json.Unmarshaler |
| 280 | |
| 281 | // An UnmarshalTypeError describes a JSON value that was |
| 282 | // not appropriate for a value of a specific Go type. |
| 283 | type UnmarshalTypeError = json.UnmarshalTypeError |
| 284 | |
| 285 | // An UnmarshalFieldError describes a JSON object key that |
| 286 | // led to an unexported (and therefore unwritable) struct field. |
| 287 | // |
| 288 | // Deprecated: No longer used; kept for compatibility. |
| 289 | type UnmarshalFieldError = json.UnmarshalFieldError |
| 290 | |
| 291 | // An InvalidUnmarshalError describes an invalid argument passed to [Unmarshal]. |
| 292 | // (The argument to [Unmarshal] must be a non-nil pointer.) |
| 293 | type InvalidUnmarshalError = json.InvalidUnmarshalError |
| 294 | |
| 295 | // A Number represents a JSON number literal. |
| 296 | type Number = json.Number |
| 297 | |
| 298 | // Marshal returns the JSON encoding of v. |
| 299 | // |
| 300 | // Marshal traverses the value v recursively. |
| 301 | // If an encountered value implements [Marshaler] |
| 302 | // and is not a nil pointer, Marshal calls [Marshaler.MarshalJSON] |
| 303 | // to produce JSON. If no [Marshaler.MarshalJSON] method is present but the |
| 304 | // value implements [encoding.TextMarshaler] instead, Marshal calls |
| 305 | // [encoding.TextMarshaler.MarshalText] and encodes the result as a JSON string. |
| 306 | // The nil pointer exception is not strictly necessary |
| 307 | // but mimics a similar, necessary exception in the behavior of |
| 308 | // [Unmarshaler.UnmarshalJSON]. |
| 309 | // |
| 310 | // Otherwise, Marshal uses the following type-dependent default encodings: |
| 311 | // |
| 312 | // Boolean values encode as JSON booleans. |
| 313 | // |
| 314 | // Floating point, integer, and [Number] values encode as JSON numbers. |
| 315 | // NaN and +/-Inf values will return an [UnsupportedValueError]. |
| 316 | // |
| 317 | // String values encode as JSON strings coerced to valid UTF-8, |
| 318 | // replacing invalid bytes with the Unicode replacement rune. |
| 319 | // So that the JSON will be safe to embed inside HTML <script> tags, |
| 320 | // the string is encoded using [HTMLEscape], |
| 321 | // which replaces "<", ">", "&", U+2028, and U+2029 are escaped |
| 322 | // to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". |
| 323 | // This replacement can be disabled when using an [Encoder], |
| 324 | // by calling [Encoder.SetEscapeHTML](false). |
| 325 | // |
| 326 | // Array and slice values encode as JSON arrays, except that |
| 327 | // []byte encodes as a base64-encoded string, and a nil slice |
| 328 | // encodes as the null JSON value. |
| 329 | // |
| 330 | // Struct values encode as JSON objects. |
| 331 | // Each exported struct field becomes a member of the object, using the |
| 332 | // field name as the object key, unless the field is omitted for one of the |
| 333 | // reasons given below. |
| 334 | // |
| 335 | // The encoding of each struct field can be customized by the format string |
| 336 | // stored under the "json" key in the struct field's tag. |
| 337 | // The format string gives the name of the field, possibly followed by a |
| 338 | // comma-separated list of options. The name may be empty in order to |
| 339 | // specify options without overriding the default field name. |
| 340 | // |
| 341 | // The "omitempty" option specifies that the field should be omitted |
| 342 | // from the encoding if the field has an empty value, defined as |
| 343 | // false, 0, a nil pointer, a nil interface value, and any array, |
| 344 | // slice, map, or string of length zero. |
| 345 | // |
| 346 | // As a special case, if the field tag is "-", the field is always omitted. |
| 347 | // JSON names containing commas or quotes, or names identical to "" or "-", |
| 348 | // can be specified using a single-quoted string literal, where the syntax |
| 349 | // is identical to the Go grammar for a double-quoted string literal, |
| 350 | // but instead uses single quotes as the delimiters. |
| 351 | // |
| 352 | // Examples of struct field tags and their meanings: |
| 353 | // |
| 354 | // // Field appears in JSON as key "myName". |
| 355 | // Field int `json:"myName"` |
| 356 | // |
| 357 | // // Field appears in JSON as key "myName" and |
| 358 | // // the field is omitted from the object if its value is empty, |
| 359 | // // as defined above. |
| 360 | // Field int `json:"myName,omitempty"` |
| 361 | // |
| 362 | // // Field appears in JSON as key "Field" (the default), but |
| 363 | // // the field is skipped if empty. |
| 364 | // // Note the leading comma. |
| 365 | // Field int `json:",omitempty"` |
| 366 | // |
| 367 | // // Field is ignored by this package. |
| 368 | // Field int `json:"-"` |
| 369 | // |
| 370 | // // Field appears in JSON as key "-". |
| 371 | // Field int `json:"'-'"` |
| 372 | // |
| 373 | // The "omitzero" option specifies that the field should be omitted |
| 374 | // from the encoding if the field has a zero value, according to rules: |
| 375 | // |
| 376 | // 1) If the field type has an "IsZero() bool" method, that will be used to |
| 377 | // determine whether the value is zero. |
| 378 | // |
| 379 | // 2) Otherwise, the value is zero if it is the zero value for its type. |
| 380 | // |
| 381 | // If both "omitempty" and "omitzero" are specified, the field will be omitted |
| 382 | // if the value is either empty or zero (or both). |
| 383 | // |
| 384 | // The "string" option signals that a field is stored as JSON inside a |
| 385 | // JSON-encoded string. It applies only to fields of string, floating point, |
| 386 | // integer, or boolean types. This extra level of encoding is sometimes used |
| 387 | // when communicating with JavaScript programs: |
| 388 | // |
| 389 | // Int64String int64 `json:",string"` |
| 390 | // |
| 391 | // The key name will be used if it's a non-empty string consisting of |
| 392 | // only Unicode letters, digits, and ASCII punctuation except quotation |
| 393 | // marks, backslash, and comma. |
| 394 | // |
| 395 | // Embedded struct fields are usually marshaled as if their inner exported fields |
| 396 | // were fields in the outer struct, subject to the usual Go visibility rules amended |
| 397 | // as described in the next paragraph. |
| 398 | // An anonymous struct field with a name given in its JSON tag is treated as |
| 399 | // having that name, rather than being anonymous. |
| 400 | // An anonymous struct field of interface type is treated the same as having |
| 401 | // that type as its name, rather than being anonymous. |
| 402 | // |
| 403 | // The Go visibility rules for struct fields are amended for JSON when |
| 404 | // deciding which field to marshal or unmarshal. If there are |
| 405 | // multiple fields at the same level, and that level is the least |
| 406 | // nested (and would therefore be the nesting level selected by the |
| 407 | // usual Go rules), the following extra rules apply: |
| 408 | // |
| 409 | // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, |
| 410 | // even if there are multiple untagged fields that would otherwise conflict. |
| 411 | // |
| 412 | // 2) If there is exactly one field (tagged or not according to the first rule), that is selected. |
| 413 | // |
| 414 | // 3) Otherwise there are multiple fields, and all are ignored; no error occurs. |
| 415 | // |
| 416 | // Handling of anonymous struct fields is new in Go 1.1. |
| 417 | // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of |
| 418 | // an anonymous struct field in both current and earlier versions, give the field |
| 419 | // a JSON tag of "-". |
| 420 | // |
| 421 | // Map values encode as JSON objects. The map's key type must either be a |
| 422 | // string, an integer type, or implement [encoding.TextMarshaler]. The map keys |
| 423 | // are sorted and used as JSON object keys by applying the following rules, |
| 424 | // subject to the UTF-8 coercion described for string values above: |
| 425 | // - keys of any string type are used directly |
| 426 | // - keys that implement [encoding.TextMarshaler] are marshaled |
| 427 | // - integer keys are converted to strings |
| 428 | // |
| 429 | // Pointer values encode as the value pointed to. |
| 430 | // A nil pointer encodes as the null JSON value. |
| 431 | // |
| 432 | // Interface values encode as the value contained in the interface. |
| 433 | // A nil interface value encodes as the null JSON value. |
| 434 | // |
| 435 | // Channel, complex, and function values cannot be encoded in JSON. |
| 436 | // Attempting to encode such a value causes Marshal to return |
| 437 | // an [UnsupportedTypeError]. |
| 438 | // |
| 439 | // JSON cannot represent cyclic data structures and Marshal does not |
| 440 | // handle them. Passing cyclic structures to Marshal will result in |
| 441 | // an error. |
| 442 | func Marshal(v any) ([]byte, error) { |
| 443 | return json.Marshal(v) |
| 444 | } |
| 445 | |
| 446 | // MarshalIndent is like [Marshal] but applies [Indent] to format the output. |
| 447 | // Each JSON element in the output will begin on a new line beginning with prefix |
| 448 | // followed by one or more copies of indent according to the indentation nesting. |
| 449 | func MarshalIndent(v any, prefix, indent string) ([]byte, error) { |
| 450 | return json.MarshalIndent(v, prefix, indent) |
| 451 | } |
| 452 | |
| 453 | // Marshaler is the interface implemented by types that |
| 454 | // can marshal themselves into valid JSON. |
| 455 | type Marshaler = json.Marshaler |
| 456 | |
| 457 | // An UnsupportedTypeError is returned by [Marshal] when attempting |
| 458 | // to encode an unsupported value type. |
| 459 | type UnsupportedTypeError = json.UnsupportedTypeError |
| 460 | |
| 461 | // An UnsupportedValueError is returned by [Marshal] when attempting |
| 462 | // to encode an unsupported value. |
| 463 | type UnsupportedValueError = json.UnsupportedValueError |
| 464 | |
| 465 | // Before Go 1.2, an InvalidUTF8Error was returned by [Marshal] when |
| 466 | // attempting to encode a string value with invalid UTF-8 sequences. |
| 467 | // As of Go 1.2, [Marshal] instead coerces the string to valid UTF-8 by |
| 468 | // replacing invalid bytes with the Unicode replacement rune U+FFFD. |
| 469 | // |
| 470 | // Deprecated: No longer used; kept for compatibility. |
| 471 | type InvalidUTF8Error = json.InvalidUTF8Error |
| 472 | |
| 473 | // A MarshalerError represents an error from calling a |
| 474 | // [Marshaler.MarshalJSON] or [encoding.TextMarshaler.MarshalText] method. |
| 475 | type MarshalerError = json.MarshalerError |
| 476 | |
| 477 | // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 |
| 478 | // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 |
| 479 | // so that the JSON will be safe to embed inside HTML <script> tags. |
| 480 | // For historical reasons, web browsers don't honor standard HTML |
| 481 | // escaping within <script> tags, so an alternative JSON encoding must be used. |
| 482 | func HTMLEscape(dst *bytes.Buffer, src []byte) { |
| 483 | json.HTMLEscape(dst, src) |
| 484 | } |
| 485 | |
| 486 | // Compact appends to dst the JSON-encoded src with |
| 487 | // insignificant space characters elided. |
| 488 | func Compact(dst *bytes.Buffer, src []byte) error { |
| 489 | return json.Compact(dst, src) |
| 490 | } |
| 491 | |
| 492 | // Indent appends to dst an indented form of the JSON-encoded src. |
| 493 | // Each element in a JSON object or array begins on a new, |
| 494 | // indented line beginning with prefix followed by one or more |
| 495 | // copies of indent according to the indentation nesting. |
| 496 | // The data appended to dst does not begin with the prefix nor |
| 497 | // any indentation, to make it easier to embed inside other formatted JSON data. |
| 498 | // Although leading space characters (space, tab, carriage return, newline) |
| 499 | // at the beginning of src are dropped, trailing space characters |
| 500 | // at the end of src are preserved and copied to dst. |
| 501 | // For example, if src has no trailing spaces, neither will dst; |
| 502 | // if src ends in a trailing newline, so will dst. |
| 503 | func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { |
| 504 | return json.Indent(dst, src, prefix, indent) |
| 505 | } |
| 506 | |
| 507 | // Options are a set of options to configure the v2 "json" package |
| 508 | // to operate with v1 semantics for particular features. |
| 509 | // Values of this type can be passed to v2 functions like |
| 510 | // [jsonv2.Marshal] or [jsonv2.Unmarshal]. |
| 511 | // Instead of referencing this type, use [jsonv2.Options]. |
| 512 | // |
| 513 | // See the "Migrating to v2" section for guidance on how to migrate usage |
| 514 | // of "json" from using v1 to using v2 instead. |
| 515 | type Options = json.Options |
| 516 | |
| 517 | // DefaultOptionsV1 is the full set of all options that define v1 semantics. |
| 518 | // It is equivalent to the following boolean options being set to true: |
| 519 | // |
| 520 | // - [CallMethodsWithLegacySemantics] |
| 521 | // - [FormatByteArrayAsArray] |
| 522 | // - [FormatBytesWithLegacySemantics] |
| 523 | // - [FormatDurationAsNano] |
| 524 | // - [MatchCaseSensitiveDelimiter] |
| 525 | // - [MergeWithLegacySemantics] |
| 526 | // - [OmitEmptyWithLegacySemantics] |
| 527 | // - [ParseBytesWithLooseRFC4648] |
| 528 | // - [ParseTimeWithLooseRFC3339] |
| 529 | // - [ReportErrorsWithLegacySemantics] |
| 530 | // - [StringifyWithLegacySemantics] |
| 531 | // - [UnmarshalArrayFromAnyLength] |
| 532 | // - [jsonv2.Deterministic] |
| 533 | // - [jsonv2.FormatNilMapAsNull] |
| 534 | // - [jsonv2.FormatNilSliceAsNull] |
| 535 | // - [jsonv2.MatchCaseInsensitiveNames] |
| 536 | // - [jsontext.AllowDuplicateNames] |
| 537 | // - [jsontext.AllowInvalidUTF8] |
| 538 | // - [jsontext.EscapeForHTML] |
| 539 | // - [jsontext.EscapeForJS] |
| 540 | // - [jsontext.PreserveRawStrings] |
| 541 | // |
| 542 | // All other options are not present. |
| 543 | // |
| 544 | // The [Marshal] and [Unmarshal] functions in this package are |
| 545 | // semantically identical to calling the v2 equivalents with this option: |
| 546 | // |
| 547 | // jsonv2.Marshal(v, jsonv1.DefaultOptionsV1()) |
| 548 | // jsonv2.Unmarshal(b, v, jsonv1.DefaultOptionsV1()) |
| 549 | func DefaultOptionsV1() Options { |
| 550 | return json.DefaultOptionsV1() |
| 551 | } |
| 552 | |
| 553 | // CallMethodsWithLegacySemantics specifies that calling of type-provided |
| 554 | // marshal and unmarshal methods follow legacy semantics: |
| 555 | // |
| 556 | // - When marshaling, a marshal method declared on a pointer receiver |
| 557 | // is only called if the Go value is addressable. |
| 558 | // Values obtained from an interface or map element are not addressable. |
| 559 | // Values obtained from a pointer or slice element are addressable. |
| 560 | // Values obtained from an array element or struct field inherit |
| 561 | // the addressability of the parent. In contrast, the v2 semantic |
| 562 | // is to always call marshal methods regardless of addressability. |
| 563 | // |
| 564 | // - When marshaling or unmarshaling, the [Marshaler] or [Unmarshaler] |
| 565 | // methods are ignored for map keys. However, [encoding.TextMarshaler] |
| 566 | // or [encoding.TextUnmarshaler] are still callable. |
| 567 | // In contrast, the v2 semantic is to serialize map keys |
| 568 | // like any other value (with regard to calling methods), |
| 569 | // which may include calling [Marshaler] or [Unmarshaler] methods, |
| 570 | // where it is the implementation's responsibility to represent the |
| 571 | // Go value as a JSON string (as required for JSON object names). |
| 572 | // |
| 573 | // - When marshaling, if a map key value implements a marshal method |
| 574 | // and is a nil pointer, then it is serialized as an empty JSON string. |
| 575 | // In contrast, the v2 semantic is to report an error. |
| 576 | // |
| 577 | // - When marshaling, if an interface type implements a marshal method |
| 578 | // and the interface value is a nil pointer to a concrete type, |
| 579 | // then the marshal method is always called. |
| 580 | // In contrast, the v2 semantic is to never directly call methods |
| 581 | // on interface values and to instead defer evaluation based upon |
| 582 | // the underlying concrete value. Similar to non-interface values, |
| 583 | // marshal methods are not called on nil pointers and |
| 584 | // are instead serialized as a JSON null. |
| 585 | // |
| 586 | // This affects either marshaling or unmarshaling. |
| 587 | // The v1 default is true. |
| 588 | func CallMethodsWithLegacySemantics(v bool) Options { |
| 589 | return json.CallMethodsWithLegacySemantics(v) |
| 590 | } |
| 591 | |
| 592 | // FormatByteArrayAsArray specifies that a Go [N]byte is |
| 593 | // formatted as as a normal Go array in contrast to the v2 default of |
| 594 | // formatting [N]byte as using binary data encoding (RFC 4648). |
| 595 | // If a struct field has a `format` tag option, |
| 596 | // then the specified formatting takes precedence. |
| 597 | // |
| 598 | // This affects either marshaling or unmarshaling. |
| 599 | // The v1 default is true. |
| 600 | func FormatByteArrayAsArray(v bool) Options { |
| 601 | return json.FormatByteArrayAsArray(v) |
| 602 | } |
| 603 | |
| 604 | // FormatBytesWithLegacySemantics specifies that handling of |
| 605 | // []~byte and [N]~byte types follow legacy semantics: |
| 606 | // |
| 607 | // - A Go []~byte is to be treated as using some form of |
| 608 | // binary data encoding (RFC 4648) in contrast to the v2 default |
| 609 | // of only treating []byte as such. In particular, v2 does not |
| 610 | // treat slices of named byte types as representing binary data. |
| 611 | // |
| 612 | // - When marshaling, if a named byte implements a marshal method, |
| 613 | // then the slice is serialized as a JSON array of elements, |
| 614 | // each of which call the marshal method. |
| 615 | // |
| 616 | // - When unmarshaling, if the input is a JSON array, |
| 617 | // then unmarshal into the []~byte as if it were a normal Go slice. |
| 618 | // In contrast, the v2 default is to report an error unmarshaling |
| 619 | // a JSON array when expecting some form of binary data encoding. |
| 620 | // |
| 621 | // This affects either marshaling or unmarshaling. |
| 622 | // The v1 default is true. |
| 623 | func FormatBytesWithLegacySemantics(v bool) Options { |
| 624 | return json.FormatBytesWithLegacySemantics(v) |
| 625 | } |
| 626 | |
| 627 | // FormatDurationAsNano specifies that a [time.Duration] is |
| 628 | // formatted as a JSON number representing the number of nanoseconds |
| 629 | // in contrast to the v2 default of reporting an error. |
| 630 | // If a duration field has a `format` tag option, |
| 631 | // then the specified formatting takes precedence. |
| 632 | // |
| 633 | // This affects either marshaling or unmarshaling. |
| 634 | // The v1 default is true. |
| 635 | func FormatDurationAsNano(v bool) Options { |
| 636 | return json.FormatDurationAsNano(v) |
| 637 | } |
| 638 | |
| 639 | // MatchCaseSensitiveDelimiter specifies that underscores and dashes are |
| 640 | // not to be ignored when performing case-insensitive name matching which |
| 641 | // occurs under [jsonv2.MatchCaseInsensitiveNames] or the `case:ignore` tag option. |
| 642 | // Thus, case-insensitive name matching is identical to [strings.EqualFold]. |
| 643 | // Use of this option diminishes the ability of case-insensitive matching |
| 644 | // to be able to match common case variants (e.g, "foo_bar" with "fooBar"). |
| 645 | // |
| 646 | // This affects either marshaling or unmarshaling. |
| 647 | // The v1 default is true. |
| 648 | func MatchCaseSensitiveDelimiter(v bool) Options { |
| 649 | return json.MatchCaseSensitiveDelimiter(v) |
| 650 | } |
| 651 | |
| 652 | // MergeWithLegacySemantics specifies that unmarshaling into a non-zero |
| 653 | // Go value follows legacy semantics: |
| 654 | // |
| 655 | // - When unmarshaling a JSON null, this preserves the original Go value |
| 656 | // if the kind is a bool, int, uint, float, string, array, or struct. |
| 657 | // Otherwise, it zeros the Go value. |
| 658 | // In contrast, the default v2 behavior is to consistently and always |
| 659 | // zero the Go value when unmarshaling a JSON null into it. |
| 660 | // |
| 661 | // - When unmarshaling a JSON value other than null, this merges into |
| 662 | // the original Go value for array elements, slice elements, |
| 663 | // struct fields (but not map values), |
| 664 | // pointer values, and interface values (only if a non-nil pointer). |
| 665 | // In contrast, the default v2 behavior is to merge into the Go value |
| 666 | // for struct fields, map values, pointer values, and interface values. |
| 667 | // In general, the v2 semantic merges when unmarshaling a JSON object, |
| 668 | // otherwise it replaces the original value. |
| 669 | // |
| 670 | // This only affects unmarshaling and is ignored when marshaling. |
| 671 | // The v1 default is true. |
| 672 | func MergeWithLegacySemantics(v bool) Options { |
| 673 | return json.MergeWithLegacySemantics(v) |
| 674 | } |
| 675 | |
| 676 | // OmitEmptyWithLegacySemantics specifies that the `omitempty` tag option |
| 677 | // follows a definition of empty where a field is omitted if the Go value is |
| 678 | // false, 0, a nil pointer, a nil interface value, |
| 679 | // or any empty array, slice, map, or string. |
| 680 | // This overrides the v2 semantic where a field is empty if the value |
| 681 | // marshals as a JSON null or an empty JSON string, object, or array. |
| 682 | // |
| 683 | // The v1 and v2 definitions of `omitempty` are practically the same for |
| 684 | // Go strings, slices, arrays, and maps. Usages of `omitempty` on |
| 685 | // Go bools, ints, uints floats, pointers, and interfaces should migrate to use |
| 686 | // the `omitzero` tag option, which omits a field if it is the zero Go value. |
| 687 | // |
| 688 | // This only affects marshaling and is ignored when unmarshaling. |
| 689 | // The v1 default is true. |
| 690 | func OmitEmptyWithLegacySemantics(v bool) Options { |
| 691 | return json.OmitEmptyWithLegacySemantics(v) |
| 692 | } |
| 693 | |
| 694 | // ParseBytesWithLooseRFC4648 specifies that when parsing |
| 695 | // binary data encoded as "base32" or "base64", |
| 696 | // to ignore the presence of '\r' and '\n' characters. |
| 697 | // In contrast, the v2 default is to report an error in order to be |
| 698 | // strictly compliant with RFC 4648, section 3.3, |
| 699 | // which specifies that non-alphabet characters must be rejected. |
| 700 | // |
| 701 | // This only affects unmarshaling and is ignored when marshaling. |
| 702 | // The v1 default is true. |
| 703 | func ParseBytesWithLooseRFC4648(v bool) Options { |
| 704 | return json.ParseBytesWithLooseRFC4648(v) |
| 705 | } |
| 706 | |
| 707 | // ParseTimeWithLooseRFC3339 specifies that a [time.Time] |
| 708 | // parses according to loose adherence to RFC 3339. |
| 709 | // In particular, it permits historically incorrect representations, |
| 710 | // allowing for deviations in hour format, sub-second separator, |
| 711 | // and timezone representation. In contrast, the default v2 behavior |
| 712 | // is to strictly comply with the grammar specified in RFC 3339. |
| 713 | // |
| 714 | // This only affects unmarshaling and is ignored when marshaling. |
| 715 | // The v1 default is true. |
| 716 | func ParseTimeWithLooseRFC3339(v bool) Options { |
| 717 | return json.ParseTimeWithLooseRFC3339(v) |
| 718 | } |
| 719 | |
| 720 | // ReportErrorsWithLegacySemantics specifies that Marshal and Unmarshal |
| 721 | // should report errors with legacy semantics: |
| 722 | // |
| 723 | // - When marshaling or unmarshaling, the returned error values are |
| 724 | // usually of types such as [SyntaxError], [MarshalerError], |
| 725 | // [UnsupportedTypeError], [UnsupportedValueError], |
| 726 | // [InvalidUnmarshalError], or [UnmarshalTypeError]. |
| 727 | // In contrast, the v2 semantic is to always return errors as either |
| 728 | // [jsonv2.SemanticError] or [jsontext.SyntacticError]. |
| 729 | // |
| 730 | // - When marshaling, if a user-defined marshal method reports an error, |
| 731 | // it is always wrapped in a [MarshalerError], even if the error itself |
| 732 | // is already a [MarshalerError], which may lead to multiple redundant |
| 733 | // layers of wrapping. In contrast, the v2 semantic is to |
| 734 | // always wrap an error within [jsonv2.SemanticError] |
| 735 | // unless it is already a semantic error. |
| 736 | // |
| 737 | // - When unmarshaling, if a user-defined unmarshal method reports an error, |
| 738 | // it is never wrapped and reported verbatim. In contrast, the v2 semantic |
| 739 | // is to always wrap an error within [jsonv2.SemanticError] |
| 740 | // unless it is already a semantic error. |
| 741 | // |
| 742 | // - When marshaling or unmarshaling, if a Go struct contains type errors |
| 743 | // (e.g., conflicting names or malformed field tags), then such errors |
| 744 | // are ignored and the Go struct uses a best-effort representation. |
| 745 | // In contrast, the v2 semantic is to report a runtime error. |
| 746 | // |
| 747 | // - When unmarshaling, the syntactic structure of the JSON input |
| 748 | // is fully validated before performing the semantic unmarshaling |
| 749 | // of the JSON data into the Go value. Practically speaking, |
| 750 | // this means that JSON input with syntactic errors do not result |
| 751 | // in any mutations of the target Go value. In contrast, the v2 semantic |
| 752 | // is to perform a streaming decode and gradually unmarshal the JSON input |
| 753 | // into the target Go value, which means that the Go value may be |
| 754 | // partially mutated when a syntactic error is encountered. |
| 755 | // |
| 756 | // - When unmarshaling, a semantic error does not immediately terminate the |
| 757 | // unmarshal procedure, but rather evaluation continues. |
| 758 | // When unmarshal returns, only the first semantic error is reported. |
| 759 | // In contrast, the v2 semantic is to terminate unmarshal the moment |
| 760 | // an error is encountered. |
| 761 | // |
| 762 | // This affects either marshaling or unmarshaling. |
| 763 | // The v1 default is true. |
| 764 | func ReportErrorsWithLegacySemantics(v bool) Options { |
| 765 | return json.ReportErrorsWithLegacySemantics(v) |
| 766 | } |
| 767 | |
| 768 | // StringifyWithLegacySemantics specifies that the `string` tag option |
| 769 | // may stringify bools and string values. It only takes effect on fields |
| 770 | // where the top-level type is a bool, string, numeric kind, or a pointer to |
| 771 | // such a kind. Specifically, `string` will not stringify bool, string, |
| 772 | // or numeric kinds within a composite data type |
| 773 | // (e.g., array, slice, struct, map, or interface). |
| 774 | // |
| 775 | // When marshaling, such Go values are serialized as their usual |
| 776 | // JSON representation, but quoted within a JSON string. |
| 777 | // When unmarshaling, such Go values must be deserialized from |
| 778 | // a JSON string containing their usual JSON representation or |
| 779 | // Go number representation for that numeric kind. |
| 780 | // Note that the Go number grammar is a superset of the JSON number grammar. |
| 781 | // A JSON null quoted in a JSON string is a valid substitute for JSON null |
| 782 | // while unmarshaling into a Go value that `string` takes effect on. |
| 783 | // |
| 784 | // This affects either marshaling or unmarshaling. |
| 785 | // The v1 default is true. |
| 786 | func StringifyWithLegacySemantics(v bool) Options { |
| 787 | return json.StringifyWithLegacySemantics(v) |
| 788 | } |
| 789 | |
| 790 | // UnmarshalArrayFromAnyLength specifies that Go arrays can be unmarshaled |
| 791 | // from input JSON arrays of any length. If the JSON array is too short, |
| 792 | // then the remaining Go array elements are zeroed. If the JSON array |
| 793 | // is too long, then the excess JSON array elements are skipped over. |
| 794 | // |
| 795 | // This only affects unmarshaling and is ignored when marshaling. |
| 796 | // The v1 default is true. |
| 797 | func UnmarshalArrayFromAnyLength(v bool) Options { |
| 798 | return json.UnmarshalArrayFromAnyLength(v) |
| 799 | } |
| 800 | |
| 801 | // Valid reports whether data is a valid JSON encoding. |
| 802 | func Valid(data []byte) bool { |
| 803 | return json.Valid(data) |
| 804 | } |
| 805 | |
| 806 | // A SyntaxError is a description of a JSON syntax error. |
| 807 | // [Unmarshal] will return a SyntaxError if the JSON can't be parsed. |
| 808 | type SyntaxError = json.SyntaxError |
| 809 | |
| 810 | // A Decoder reads and decodes JSON values from an input stream. |
| 811 | type Decoder = json.Decoder |
| 812 | |
| 813 | // NewDecoder returns a new decoder that reads from r. |
| 814 | // |
| 815 | // The decoder introduces its own buffering and may |
| 816 | // read data from r beyond the JSON values requested. |
| 817 | func NewDecoder(r io.Reader) *Decoder { |
| 818 | return json.NewDecoder(r) |
| 819 | } |
| 820 | |
| 821 | // An Encoder writes JSON values to an output stream. |
| 822 | type Encoder = json.Encoder |
| 823 | |
| 824 | // NewEncoder returns a new encoder that writes to w. |
| 825 | func NewEncoder(w io.Writer) *Encoder { |
| 826 | return json.NewEncoder(w) |
| 827 | } |
| 828 | |
| 829 | // RawMessage is a raw encoded JSON value. |
| 830 | // It implements [Marshaler] and [Unmarshaler] and can |
| 831 | // be used to delay JSON decoding or precompute a JSON encoding. |
| 832 | type RawMessage = json.RawMessage |
| 833 | |
| 834 | // A Token holds a value of one of these types: |
| 835 | // |
| 836 | // - [Delim], for the four JSON delimiters [ ] { } |
| 837 | // - bool, for JSON booleans |
| 838 | // - float64, for JSON numbers |
| 839 | // - [Number], for JSON numbers |
| 840 | // - string, for JSON string literals |
| 841 | // - nil, for JSON null |
| 842 | type Token = json.Token |
| 843 | |
| 844 | // A Delim is a JSON array or object delimiter, one of [ ] { or }. |
| 845 | type Delim = json.Delim |