Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/doc.go

raw
1 // Copyright 2020 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 // Package json implements semantic processing of JSON as specified in RFC 8259.
6 // JSON is a simple data interchange format that can represent
7 // primitive data types such as booleans, strings, and numbers,
8 // in addition to structured data types such as objects and arrays.
9 //
10 // [Marshal] and [Unmarshal] encode and decode Go values
11 // to/from JSON text contained within a []byte.
12 // [MarshalWrite] and [UnmarshalRead] operate on JSON text
13 // by writing to or reading from an [io.Writer] or [io.Reader].
14 // [MarshalEncode] and [UnmarshalDecode] operate on JSON text
15 // by encoding to or decoding from a [jsontext.Encoder] or [jsontext.Decoder].
16 // [Options] may be passed to each of the marshal or unmarshal functions
17 // to configure the semantic behavior of marshaling and unmarshaling
18 // (i.e., alter how JSON data is understood as Go data and vice versa).
19 // [jsontext.Options] may also be passed to the marshal or unmarshal functions
20 // to configure the syntactic behavior of encoding or decoding.
21 //
22 // The data types of JSON are mapped to/from the data types of Go based on
23 // the closest logical equivalent between the two type systems. For example,
24 // a JSON boolean corresponds with a Go bool,
25 // a JSON string corresponds with a Go string,
26 // a JSON number corresponds with a Go int, uint or float,
27 // a JSON array corresponds with a Go slice or array, and
28 // a JSON object corresponds with a Go struct or map.
29 // See the documentation on [Marshal] and [Unmarshal] for a comprehensive list
30 // of how the JSON and Go type systems correspond.
31 //
32 // Arbitrary Go types can customize their JSON representation by implementing
33 // [Marshaler], [MarshalerTo], [Unmarshaler], or [UnmarshalerFrom].
34 // This provides authors of Go types with control over how their types are
35 // serialized as JSON. Alternatively, users can implement functions that match
36 // [MarshalFunc], [MarshalToFunc], [UnmarshalFunc], or [UnmarshalFromFunc]
37 // to specify the JSON representation for arbitrary types.
38 // This provides callers of JSON functionality with control over
39 // how any arbitrary type is serialized as JSON.
40 //
41 // # JSON Representation of Go structs
42 //
43 // A Go struct is naturally represented as a JSON object,
44 // where each Go struct field corresponds with a JSON object member.
45 // When marshaling, all Go struct fields are recursively encoded in depth-first
46 // order as JSON object members except those that are ignored or omitted.
47 // When unmarshaling, JSON object members are recursively decoded
48 // into the corresponding Go struct fields.
49 // Object members that do not match any struct fields,
50 // also known as “unknown members”, are ignored by default or rejected
51 // if [RejectUnknownMembers] is specified.
52 //
53 // The representation of each struct field can be customized in the
54 // "json" struct field tag, where the tag is a comma separated list of options.
55 // As a special case, if the entire tag is `json:"-"`,
56 // then the field is ignored with regard to its JSON representation.
57 // Some options also have equivalent behavior controlled by a caller-specified [Options].
58 // Field-specified options take precedence over caller-specified options.
59 //
60 // The first option is the JSON object name override for the Go struct field.
61 // If the name is not specified, then the Go struct field name
62 // is used as the JSON object name. JSON names containing commas or quotes,
63 // or names identical to "" or "-", can be specified using
64 // a single-quoted string literal, where the syntax is identical to
65 // the Go grammar for a double-quoted string literal,
66 // but instead uses single quotes as the delimiters.
67 // By default, unmarshaling uses case-sensitive matching to identify
68 // the Go struct field associated with a JSON object name.
69 //
70 // After the name, the following tag options are supported:
71 //
72 // - omitzero: When marshaling, the "omitzero" option specifies that
73 // the struct field should be omitted if the field value is zero
74 // as determined by the "IsZero() bool" method if present,
75 // otherwise based on whether the field is the zero Go value.
76 // This option has no effect when unmarshaling.
77 //
78 // - omitempty: When marshaling, the "omitempty" option specifies that
79 // the struct field should be omitted if the field value would have been
80 // encoded as a JSON null, empty string, empty object, or empty array.
81 // This option has no effect when unmarshaling.
82 //
83 // - string: The "string" option specifies that [StringifyNumbers]
84 // be set when marshaling or unmarshaling a struct field value.
85 // This causes numeric types to be encoded as a JSON number
86 // within a JSON string, and to be decoded from a JSON string
87 // containing the JSON number without any surrounding whitespace.
88 // This extra level of encoding is often necessary since
89 // many JSON parsers cannot precisely represent 64-bit integers.
90 //
91 // - case: When unmarshaling, the "case" option specifies how
92 // JSON object names are matched with the JSON name for Go struct fields.
93 // The option is a key-value pair specified as "case:value" where
94 // the value must either be 'ignore' or 'strict'.
95 // The 'ignore' value specifies that matching is case-insensitive
96 // where dashes and underscores are also ignored. If multiple fields match,
97 // the first declared field in breadth-first order takes precedence.
98 // The 'strict' value specifies that matching is case-sensitive.
99 // This takes precedence over the [MatchCaseInsensitiveNames] option.
100 //
101 // - inline: The "inline" option specifies that
102 // the JSON representable content of this field type is to be promoted
103 // as if they were specified in the parent struct.
104 // It is the JSON equivalent of Go struct embedding.
105 // A Go embedded field is implicitly inlined unless an explicit JSON name
106 // is specified. The inlined field must be a Go struct
107 // (that does not implement any JSON methods), [jsontext.Value],
108 // map[~string]T, or an unnamed pointer to such types. When marshaling,
109 // inlined fields from a pointer type are omitted if it is nil.
110 // Inlined fields of type [jsontext.Value] and map[~string]T are called
111 // “inlined fallbacks” as they can represent all possible
112 // JSON object members not directly handled by the parent struct.
113 // Only one inlined fallback field may be specified in a struct,
114 // while many non-fallback fields may be specified. This option
115 // must not be specified with any other option (including the JSON name).
116 //
117 // - unknown: The "unknown" option is a specialized variant
118 // of the inlined fallback to indicate that this Go struct field
119 // contains any number of unknown JSON object members. The field type must
120 // be a [jsontext.Value], map[~string]T, or an unnamed pointer to such types.
121 // If [DiscardUnknownMembers] is specified when marshaling,
122 // the contents of this field are ignored.
123 // If [RejectUnknownMembers] is specified when unmarshaling,
124 // any unknown object members are rejected regardless of whether
125 // an inlined fallback with the "unknown" option exists. This option
126 // must not be specified with any other option (including the JSON name).
127 //
128 // - format: The "format" option specifies a format flag
129 // used to specialize the formatting of the field value.
130 // The option is a key-value pair specified as "format:value" where
131 // the value must be either a literal consisting of letters and numbers
132 // (e.g., "format:RFC3339") or a single-quoted string literal
133 // (e.g., "format:'2006-01-02'"). The interpretation of the format flag
134 // is determined by the struct field type.
135 //
136 // The "omitzero" and "omitempty" options are mostly semantically identical.
137 // The former is defined in terms of the Go type system,
138 // while the latter in terms of the JSON type system.
139 // Consequently they behave differently in some circumstances.
140 // For example, only a nil slice or map is omitted under "omitzero", while
141 // an empty slice or map is omitted under "omitempty" regardless of nilness.
142 // The "omitzero" option is useful for types with a well-defined zero value
143 // (e.g., [net/netip.Addr]) or have an IsZero method (e.g., [time.Time.IsZero]).
144 //
145 // Every Go struct corresponds to a list of JSON representable fields
146 // which is constructed by performing a breadth-first search over
147 // all struct fields (excluding unexported or ignored fields),
148 // where the search recursively descends into inlined structs.
149 // The set of non-inlined fields in a struct must have unique JSON names.
150 // If multiple fields all have the same JSON name, then the one
151 // at shallowest depth takes precedence and the other fields at deeper depths
152 // are excluded from the list of JSON representable fields.
153 // If multiple fields at the shallowest depth have the same JSON name,
154 // but exactly one is explicitly tagged with a JSON name,
155 // then that field takes precedence and all others are excluded from the list.
156 // This is analogous to Go visibility rules for struct field selection
157 // with embedded struct types.
158 //
159 // Marshaling or unmarshaling a non-empty struct
160 // without any JSON representable fields results in a [SemanticError].
161 // Unexported fields must not have any `json` tags except for `json:"-"`.
162 //
163 // # Security Considerations
164 //
165 // JSON is frequently used as a data interchange format to communicate
166 // between different systems, possibly implemented in different languages.
167 // For interoperability and security reasons, it is important that
168 // all implementations agree upon the semantic meaning of the data.
169 //
170 // [For example, suppose we have two micro-services.]
171 // The first service is responsible for authenticating a JSON request,
172 // while the second service is responsible for executing the request
173 // (having assumed that the prior service authenticated the request).
174 // If an attacker were able to maliciously craft a JSON request such that
175 // both services believe that the same request is from different users,
176 // it could bypass the authenticator with valid credentials for one user,
177 // but maliciously perform an action on behalf of a different user.
178 //
179 // According to RFC 8259, there unfortunately exist many JSON texts
180 // that are syntactically valid but semantically ambiguous.
181 // For example, the standard does not define how to interpret duplicate
182 // names within an object.
183 //
184 // The v1 [encoding/json] and [encoding/json/v2] packages
185 // interpret some inputs in different ways. In particular:
186 //
187 // - The standard specifies that JSON must be encoded using UTF-8.
188 // By default, v1 replaces invalid bytes of UTF-8 in JSON strings
189 // with the Unicode replacement character,
190 // while v2 rejects inputs with invalid UTF-8.
191 // To change the default, specify the [jsontext.AllowInvalidUTF8] option.
192 // The replacement of invalid UTF-8 is a form of data corruption
193 // that alters the precise meaning of strings.
194 //
195 // - The standard does not specify a particular behavior when
196 // duplicate names are encountered within a JSON object,
197 // which means that different implementations may behave differently.
198 // By default, v1 allows for the presence of duplicate names,
199 // while v2 rejects duplicate names.
200 // To change the default, specify the [jsontext.AllowDuplicateNames] option.
201 // If allowed, object members are processed in the order they are observed,
202 // meaning that later values will replace or be merged into prior values,
203 // depending on the Go value type.
204 //
205 // - The standard defines a JSON object as an unordered collection of name/value pairs.
206 // While ordering can be observed through the underlying [jsontext] API,
207 // both v1 and v2 generally avoid exposing the ordering.
208 // No application should semantically depend on the order of object members.
209 // Allowing duplicate names is a vector through which ordering of members
210 // can accidentally be observed and depended upon.
211 //
212 // - The standard suggests that JSON object names are typically compared
213 // based on equality of the sequence of Unicode code points,
214 // which implies that comparing names is often case-sensitive.
215 // When unmarshaling a JSON object into a Go struct,
216 // by default, v1 uses a (loose) case-insensitive match on the name,
217 // while v2 uses a (strict) case-sensitive match on the name.
218 // To change the default, specify the [MatchCaseInsensitiveNames] option.
219 // The use of case-insensitive matching provides another vector through
220 // which duplicate names can occur. Allowing case-insensitive matching
221 // means that v1 or v2 might interpret JSON objects differently from most
222 // other JSON implementations (which typically use a case-sensitive match).
223 //
224 // - The standard does not specify a particular behavior when
225 // an unknown name in a JSON object is encountered.
226 // When unmarshaling a JSON object into a Go struct, by default
227 // both v1 and v2 ignore unknown names and their corresponding values.
228 // To change the default, specify the [RejectUnknownMembers] option.
229 //
230 // - The standard suggests that implementations may use a float64
231 // to represent a JSON number. Consequently, large JSON integers
232 // may lose precision when stored as a floating-point type.
233 // Both v1 and v2 correctly preserve precision when marshaling and
234 // unmarshaling a concrete integer type. However, even if v1 and v2
235 // preserve precision for concrete types, other JSON implementations
236 // may not be able to preserve precision for outputs produced by v1 or v2.
237 // The `string` tag option can be used to specify that an integer type
238 // is to be quoted within a JSON string to avoid loss of precision.
239 // Furthermore, v1 and v2 may still lose precision when unmarshaling
240 // into an any interface value, where unmarshal uses a float64
241 // by default to represent a JSON number.
242 // To change the default, specify the [WithUnmarshalers] option
243 // with a custom unmarshaler that pre-populates the interface value
244 // with a concrete Go type that can preserve precision.
245 //
246 // RFC 8785 specifies a canonical form for any JSON text,
247 // which explicitly defines specific behaviors that RFC 8259 leaves undefined.
248 // In theory, if a text can successfully [jsontext.Value.Canonicalize]
249 // without changing the semantic meaning of the data, then it provides a
250 // greater degree of confidence that the data is more secure and interoperable.
251 //
252 // The v2 API generally chooses more secure defaults than v1,
253 // but care should still be taken with large integers or unknown members.
254 //
255 // [For example, suppose we have two micro-services.]: https://www.youtube.com/watch?v=avilmOcHKHE&t=1057s
256 package json
257
258 // requireKeyedLiterals can be embedded in a struct to require keyed literals.
259 type requireKeyedLiterals struct{}
260
261 // nonComparable can be embedded in a struct to prevent comparability.
262 type nonComparable [0]func()