| 1 |
package json |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
|
| 8 |
"github.com/goccy/go-json/internal/decoder" |
| 9 |
"github.com/goccy/go-json/internal/encoder" |
| 10 |
) |
| 11 |
|
| 12 |
// Marshaler is the interface implemented by types that |
| 13 |
// can marshal themselves into valid JSON. |
| 14 |
type Marshaler interface { |
| 15 |
MarshalJSON() ([]byte, error) |
| 16 |
} |
| 17 |
|
| 18 |
// MarshalerContext is the interface implemented by types that |
| 19 |
// can marshal themselves into valid JSON with context.Context. |
| 20 |
type MarshalerContext interface { |
| 21 |
MarshalJSON(context.Context) ([]byte, error) |
| 22 |
} |
| 23 |
|
| 24 |
// Unmarshaler is the interface implemented by types |
| 25 |
// that can unmarshal a JSON description of themselves. |
| 26 |
// The input can be assumed to be a valid encoding of |
| 27 |
// a JSON value. UnmarshalJSON must copy the JSON data |
| 28 |
// if it wishes to retain the data after returning. |
| 29 |
// |
| 30 |
// By convention, to approximate the behavior of Unmarshal itself, |
| 31 |
// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. |
| 32 |
type Unmarshaler interface { |
| 33 |
UnmarshalJSON([]byte) error |
| 34 |
} |
| 35 |
|
| 36 |
// UnmarshalerContext is the interface implemented by types |
| 37 |
// that can unmarshal with context.Context a JSON description of themselves. |
| 38 |
type UnmarshalerContext interface { |
| 39 |
UnmarshalJSON(context.Context, []byte) error |
| 40 |
} |
| 41 |
|
| 42 |
// Marshal returns the JSON encoding of v. |
| 43 |
// |
| 44 |
// Marshal traverses the value v recursively. |
| 45 |
// If an encountered value implements the Marshaler interface |
| 46 |
// and is not a nil pointer, Marshal calls its MarshalJSON method |
| 47 |
// to produce JSON. If no MarshalJSON method is present but the |
| 48 |
// value implements encoding.TextMarshaler instead, Marshal calls |
| 49 |
// its MarshalText method and encodes the result as a JSON string. |
| 50 |
// The nil pointer exception is not strictly necessary |
| 51 |
// but mimics a similar, necessary exception in the behavior of |
| 52 |
// UnmarshalJSON. |
| 53 |
// |
| 54 |
// Otherwise, Marshal uses the following type-dependent default encodings: |
| 55 |
// |
| 56 |
// Boolean values encode as JSON booleans. |
| 57 |
// |
| 58 |
// Floating point, integer, and Number values encode as JSON numbers. |
| 59 |
// |
| 60 |
// String values encode as JSON strings coerced to valid UTF-8, |
| 61 |
// replacing invalid bytes with the Unicode replacement rune. |
| 62 |
// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" |
| 63 |
// to keep some browsers from misinterpreting JSON output as HTML. |
| 64 |
// Ampersand "&" is also escaped to "\u0026" for the same reason. |
| 65 |
// This escaping can be disabled using an Encoder that had SetEscapeHTML(false) |
| 66 |
// called on it. |
| 67 |
// |
| 68 |
// Array and slice values encode as JSON arrays, except that |
| 69 |
// []byte encodes as a base64-encoded string, and a nil slice |
| 70 |
// encodes as the null JSON value. |
| 71 |
// |
| 72 |
// Struct values encode as JSON objects. |
| 73 |
// Each exported struct field becomes a member of the object, using the |
| 74 |
// field name as the object key, unless the field is omitted for one of the |
| 75 |
// reasons given below. |
| 76 |
// |
| 77 |
// The encoding of each struct field can be customized by the format string |
| 78 |
// stored under the "json" key in the struct field's tag. |
| 79 |
// The format string gives the name of the field, possibly followed by a |
| 80 |
// comma-separated list of options. The name may be empty in order to |
| 81 |
// specify options without overriding the default field name. |
| 82 |
// |
| 83 |
// The "omitempty" option specifies that the field should be omitted |
| 84 |
// from the encoding if the field has an empty value, defined as |
| 85 |
// false, 0, a nil pointer, a nil interface value, and any empty array, |
| 86 |
// slice, map, or string. |
| 87 |
// |
| 88 |
// As a special case, if the field tag is "-", the field is always omitted. |
| 89 |
// Note that a field with name "-" can still be generated using the tag "-,". |
| 90 |
// |
| 91 |
// Examples of struct field tags and their meanings: |
| 92 |
// |
| 93 |
// // Field appears in JSON as key "myName". |
| 94 |
// Field int `json:"myName"` |
| 95 |
// |
| 96 |
// // Field appears in JSON as key "myName" and |
| 97 |
// // the field is omitted from the object if its value is empty, |
| 98 |
// // as defined above. |
| 99 |
// Field int `json:"myName,omitempty"` |
| 100 |
// |
| 101 |
// // Field appears in JSON as key "Field" (the default), but |
| 102 |
// // the field is skipped if empty. |
| 103 |
// // Note the leading comma. |
| 104 |
// Field int `json:",omitempty"` |
| 105 |
// |
| 106 |
// // Field is ignored by this package. |
| 107 |
// Field int `json:"-"` |
| 108 |
// |
| 109 |
// // Field appears in JSON as key "-". |
| 110 |
// Field int `json:"-,"` |
| 111 |
// |
| 112 |
// The "string" option signals that a field is stored as JSON inside a |
| 113 |
// JSON-encoded string. It applies only to fields of string, floating point, |
| 114 |
// integer, or boolean types. This extra level of encoding is sometimes used |
| 115 |
// when communicating with JavaScript programs: |
| 116 |
// |
| 117 |
// Int64String int64 `json:",string"` |
| 118 |
// |
| 119 |
// The key name will be used if it's a non-empty string consisting of |
| 120 |
// only Unicode letters, digits, and ASCII punctuation except quotation |
| 121 |
// marks, backslash, and comma. |
| 122 |
// |
| 123 |
// Anonymous struct fields are usually marshaled as if their inner exported fields |
| 124 |
// were fields in the outer struct, subject to the usual Go visibility rules amended |
| 125 |
// as described in the next paragraph. |
| 126 |
// An anonymous struct field with a name given in its JSON tag is treated as |
| 127 |
// having that name, rather than being anonymous. |
| 128 |
// An anonymous struct field of interface type is treated the same as having |
| 129 |
// that type as its name, rather than being anonymous. |
| 130 |
// |
| 131 |
// The Go visibility rules for struct fields are amended for JSON when |
| 132 |
// deciding which field to marshal or unmarshal. If there are |
| 133 |
// multiple fields at the same level, and that level is the least |
| 134 |
// nested (and would therefore be the nesting level selected by the |
| 135 |
// usual Go rules), the following extra rules apply: |
| 136 |
// |
| 137 |
// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, |
| 138 |
// even if there are multiple untagged fields that would otherwise conflict. |
| 139 |
// |
| 140 |
// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. |
| 141 |
// |
| 142 |
// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. |
| 143 |
// |
| 144 |
// Handling of anonymous struct fields is new in Go 1.1. |
| 145 |
// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of |
| 146 |
// an anonymous struct field in both current and earlier versions, give the field |
| 147 |
// a JSON tag of "-". |
| 148 |
// |
| 149 |
// Map values encode as JSON objects. The map's key type must either be a |
| 150 |
// string, an integer type, or implement encoding.TextMarshaler. The map keys |
| 151 |
// are sorted and used as JSON object keys by applying the following rules, |
| 152 |
// subject to the UTF-8 coercion described for string values above: |
| 153 |
// - string keys are used directly |
| 154 |
// - encoding.TextMarshalers are marshaled |
| 155 |
// - integer keys are converted to strings |
| 156 |
// |
| 157 |
// Pointer values encode as the value pointed to. |
| 158 |
// A nil pointer encodes as the null JSON value. |
| 159 |
// |
| 160 |
// Interface values encode as the value contained in the interface. |
| 161 |
// A nil interface value encodes as the null JSON value. |
| 162 |
// |
| 163 |
// Channel, complex, and function values cannot be encoded in JSON. |
| 164 |
// Attempting to encode such a value causes Marshal to return |
| 165 |
// an UnsupportedTypeError. |
| 166 |
// |
| 167 |
// JSON cannot represent cyclic data structures and Marshal does not |
| 168 |
// handle them. Passing cyclic structures to Marshal will result in |
| 169 |
// an infinite recursion. |
| 170 |
func Marshal(v any) ([]byte, error) { |
| 171 |
return MarshalWithOption(v) |
| 172 |
} |
| 173 |
|
| 174 |
// MarshalNoEscape returns the JSON encoding of v. |
| 175 |
// |
| 176 |
// Deprecated: Use Marshal. MarshalNoEscape used to keep v from escaping to the heap, but the encoder refers to v |
| 177 |
// by its address, which is not updated when the stack of the goroutine is copied while v is being encoded. |
| 178 |
// A value left on the stack was then read from the freed stack, so MarshalNoEscape is now the same as Marshal. |
| 179 |
func MarshalNoEscape(v any) ([]byte, error) { |
| 180 |
return marshal(v) |
| 181 |
} |
| 182 |
|
| 183 |
// MarshalContext returns the JSON encoding of v with context.Context and EncodeOption. |
| 184 |
func MarshalContext(ctx context.Context, v any, optFuncs ...EncodeOptionFunc) ([]byte, error) { |
| 185 |
return marshalContext(ctx, v, optFuncs...) |
| 186 |
} |
| 187 |
|
| 188 |
// MarshalWithOption returns the JSON encoding of v with EncodeOption. |
| 189 |
func MarshalWithOption(v any, optFuncs ...EncodeOptionFunc) ([]byte, error) { |
| 190 |
return marshal(v, optFuncs...) |
| 191 |
} |
| 192 |
|
| 193 |
// MarshalIndent is like Marshal but applies Indent to format the output. |
| 194 |
// Each JSON element in the output will begin on a new line beginning with prefix |
| 195 |
// followed by one or more copies of indent according to the indentation nesting. |
| 196 |
func MarshalIndent(v any, prefix, indent string) ([]byte, error) { |
| 197 |
return MarshalIndentWithOption(v, prefix, indent) |
| 198 |
} |
| 199 |
|
| 200 |
// MarshalIndentWithOption is like Marshal but applies Indent to format the output with EncodeOption. |
| 201 |
func MarshalIndentWithOption(v any, prefix, indent string, optFuncs ...EncodeOptionFunc) ([]byte, error) { |
| 202 |
return marshalIndent(v, prefix, indent, optFuncs...) |
| 203 |
} |
| 204 |
|
| 205 |
// Unmarshal parses the JSON-encoded data and stores the result |
| 206 |
// in the value pointed to by v. If v is nil or not a pointer, |
| 207 |
// Unmarshal returns an InvalidUnmarshalError. |
| 208 |
// |
| 209 |
// Unmarshal uses the inverse of the encodings that |
| 210 |
// Marshal uses, allocating maps, slices, and pointers as necessary, |
| 211 |
// with the following additional rules: |
| 212 |
// |
| 213 |
// To unmarshal JSON into a pointer, Unmarshal first handles the case of |
| 214 |
// the JSON being the JSON literal null. In that case, Unmarshal sets |
| 215 |
// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into |
| 216 |
// the value pointed at by the pointer. If the pointer is nil, Unmarshal |
| 217 |
// allocates a new value for it to point to. |
| 218 |
// |
| 219 |
// To unmarshal JSON into a value implementing the Unmarshaler interface, |
| 220 |
// Unmarshal calls that value's UnmarshalJSON method, including |
| 221 |
// when the input is a JSON null. |
| 222 |
// Otherwise, if the value implements encoding.TextUnmarshaler |
| 223 |
// and the input is a JSON quoted string, Unmarshal calls that value's |
| 224 |
// UnmarshalText method with the unquoted form of the string. |
| 225 |
// |
| 226 |
// To unmarshal JSON into a struct, Unmarshal matches incoming object |
| 227 |
// keys to the keys used by Marshal (either the struct field name or its tag), |
| 228 |
// preferring an exact match but also accepting a case-insensitive match. By |
| 229 |
// default, object keys which don't have a corresponding struct field are |
| 230 |
// ignored (see Decoder.DisallowUnknownFields for an alternative). |
| 231 |
// |
| 232 |
// To unmarshal JSON into an interface value, |
| 233 |
// Unmarshal stores one of these in the interface value: |
| 234 |
// |
| 235 |
// bool, for JSON booleans |
| 236 |
// float64, for JSON numbers |
| 237 |
// string, for JSON strings |
| 238 |
// []interface{}, for JSON arrays |
| 239 |
// map[string]interface{}, for JSON objects |
| 240 |
// nil for JSON null |
| 241 |
// |
| 242 |
// To unmarshal a JSON array into a slice, Unmarshal resets the slice length |
| 243 |
// to zero and then appends each element to the slice. |
| 244 |
// As a special case, to unmarshal an empty JSON array into a slice, |
| 245 |
// Unmarshal replaces the slice with a new empty slice. |
| 246 |
// |
| 247 |
// To unmarshal a JSON array into a Go array, Unmarshal decodes |
| 248 |
// JSON array elements into corresponding Go array elements. |
| 249 |
// If the Go array is smaller than the JSON array, |
| 250 |
// the additional JSON array elements are discarded. |
| 251 |
// If the JSON array is smaller than the Go array, |
| 252 |
// the additional Go array elements are set to zero values. |
| 253 |
// |
| 254 |
// To unmarshal a JSON object into a map, Unmarshal first establishes a map to |
| 255 |
// use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal |
| 256 |
// reuses the existing map, keeping existing entries. Unmarshal then stores |
| 257 |
// key-value pairs from the JSON object into the map. The map's key type must |
| 258 |
// either be any string type, an integer, implement json.Unmarshaler, or |
| 259 |
// implement encoding.TextUnmarshaler. |
| 260 |
// |
| 261 |
// If a JSON value is not appropriate for a given target type, |
| 262 |
// or if a JSON number overflows the target type, Unmarshal |
| 263 |
// skips that field and completes the unmarshaling as best it can. |
| 264 |
// If no more serious errors are encountered, Unmarshal returns |
| 265 |
// an UnmarshalTypeError describing the earliest such error. In any |
| 266 |
// case, it's not guaranteed that all the remaining fields following |
| 267 |
// the problematic one will be unmarshaled into the target object. |
| 268 |
// |
| 269 |
// The JSON null value unmarshals into an interface, map, pointer, or slice |
| 270 |
// by setting that Go value to nil. Because null is often used in JSON to mean |
| 271 |
// “not present,” unmarshaling a JSON null into any other Go type has no effect |
| 272 |
// on the value and produces no error. |
| 273 |
// |
| 274 |
// When unmarshaling quoted strings, invalid UTF-8 or |
| 275 |
// invalid UTF-16 surrogate pairs are not treated as an error. |
| 276 |
// Instead, they are replaced by the Unicode replacement |
| 277 |
// character U+FFFD. |
| 278 |
func Unmarshal(data []byte, v any) error { |
| 279 |
return unmarshal(data, v) |
| 280 |
} |
| 281 |
|
| 282 |
// UnmarshalContext parses the JSON-encoded data and stores the result |
| 283 |
// in the value pointed to by v. If you implement the UnmarshalerContext interface, |
| 284 |
// call it with ctx as an argument. |
| 285 |
func UnmarshalContext(ctx context.Context, data []byte, v any, optFuncs ...DecodeOptionFunc) error { |
| 286 |
return unmarshalContext(ctx, data, v, optFuncs...) |
| 287 |
} |
| 288 |
|
| 289 |
func UnmarshalWithOption(data []byte, v any, optFuncs ...DecodeOptionFunc) error { |
| 290 |
return unmarshal(data, v, optFuncs...) |
| 291 |
} |
| 292 |
|
| 293 |
// UnmarshalNoEscape parses the JSON-encoded data and stores the result in the value pointed to by v. |
| 294 |
// |
| 295 |
// Deprecated: Use UnmarshalOf, which lets the value stay on the stack of the caller. UnmarshalNoEscape used to |
| 296 |
// keep v from escaping to the heap, but the decoder refers to v by its address, which is not updated when the |
| 297 |
// stack of the goroutine is copied while v is being decoded, so UnmarshalNoEscape is now the same as |
| 298 |
// UnmarshalWithOption. |
| 299 |
func UnmarshalNoEscape(data []byte, v any, optFuncs ...DecodeOptionFunc) error { |
| 300 |
return unmarshal(data, v, optFuncs...) |
| 301 |
} |
| 302 |
|
| 303 |
// A Token holds a value of one of these types: |
| 304 |
// |
| 305 |
// Delim, for the four JSON delimiters [ ] { } |
| 306 |
// bool, for JSON booleans |
| 307 |
// float64, for JSON numbers |
| 308 |
// Number, for JSON numbers |
| 309 |
// string, for JSON string literals |
| 310 |
// nil, for JSON null |
| 311 |
type Token = json.Token |
| 312 |
|
| 313 |
// A Number represents a JSON number literal. |
| 314 |
type Number = json.Number |
| 315 |
|
| 316 |
// RawMessage is a raw encoded JSON value. |
| 317 |
// It implements Marshaler and Unmarshaler and can |
| 318 |
// be used to delay JSON decoding or precompute a JSON encoding. |
| 319 |
type RawMessage = json.RawMessage |
| 320 |
|
| 321 |
// A Delim is a JSON array or object delimiter, one of [ ] { or }. |
| 322 |
type Delim = json.Delim |
| 323 |
|
| 324 |
// Compact appends to dst the JSON-encoded src with |
| 325 |
// insignificant space characters elided. |
| 326 |
func Compact(dst *bytes.Buffer, src []byte) error { |
| 327 |
return encoder.Compact(dst, src, false) |
| 328 |
} |
| 329 |
|
| 330 |
// Indent appends to dst an indented form of the JSON-encoded src. |
| 331 |
// Each element in a JSON object or array begins on a new, |
| 332 |
// indented line beginning with prefix followed by one or more |
| 333 |
// copies of indent according to the indentation nesting. |
| 334 |
// The data appended to dst does not begin with the prefix nor |
| 335 |
// any indentation, to make it easier to embed inside other formatted JSON data. |
| 336 |
// Although leading space characters (space, tab, carriage return, newline) |
| 337 |
// at the beginning of src are dropped, trailing space characters |
| 338 |
// at the end of src are preserved and copied to dst. |
| 339 |
// For example, if src has no trailing spaces, neither will dst; |
| 340 |
// if src ends in a trailing newline, so will dst. |
| 341 |
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { |
| 342 |
return encoder.Indent(dst, src, prefix, indent) |
| 343 |
} |
| 344 |
|
| 345 |
// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 |
| 346 |
// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 |
| 347 |
// so that the JSON will be safe to embed inside HTML <script> tags. |
| 348 |
// For historical reasons, web browsers don't honor standard HTML |
| 349 |
// escaping within <script> tags, so an alternative JSON encoding must |
| 350 |
// be used. |
| 351 |
func HTMLEscape(dst *bytes.Buffer, src []byte) { |
| 352 |
var v any |
| 353 |
dec := NewDecoder(bytes.NewBuffer(src)) |
| 354 |
dec.UseNumber() |
| 355 |
if err := dec.Decode(&v); err != nil { |
| 356 |
return |
| 357 |
} |
| 358 |
buf, _ := marshal(v) |
| 359 |
dst.Write(buf) |
| 360 |
} |
| 361 |
|
| 362 |
// Valid reports whether data is a valid JSON encoding. |
| 363 |
func Valid(data []byte) bool { |
| 364 |
// the input is checked by the grammar in the buffer of a context, which is followed by the nul byte |
| 365 |
ctx := decoder.TakeRuntimeContext() |
| 366 |
valid := decoder.Valid(ctx.SetInput(data)) |
| 367 |
decoder.ReleaseRuntimeContext(ctx) |
| 368 |
return valid |
| 369 |
} |
| 370 |
|
| 371 |
func init() { |
| 372 |
encoder.Marshal = Marshal |
| 373 |
encoder.Unmarshal = Unmarshal |
| 374 |
} |