Debian Codegraph @

json/golang_decode_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2010 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
6
7 import (
8 "bytes"
9 "encoding"
10 "errors"
11 "fmt"
12 "image"
13 "math"
14 "math/big"
15 "net"
16 "reflect"
•17 "runtime"
18 "strconv"
19 "strings"
20 "testing"
21 "time"
22 )
23
24 type T struct {
25 X string
26 Y int
27 Z int `json:"-"`
28 }
29
30 type U struct {
31 Alphabet string `json:"alpha"`
32 }
33
34 type V struct {
35 F1 any
36 F2 int32
37 F3 Number
38 F4 *VOuter
39 }
40
41 type VOuter struct {
42 V V
43 }
44
45 type W struct {
46 S SS
47 }
48
49 type P struct {
50 PP PP
51 }
52
53 type PP struct {
54 T T
55 Ts []T
56 }
57
58 type SS string
59
60 func (*SS) UnmarshalJSON(data []byte) error {
61 return &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(SS(""))}
62 }
63
64 // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and
65 // without UseNumber
66 var ifaceNumAsFloat64 = map[string]any{
67 "k1": float64(1),
68 "k2": "s",
69 "k3": []any{float64(1), float64(2.0), float64(3e-3)},
70 "k4": map[string]any{"kk1": "s", "kk2": float64(2)},
71 }
72
73 var ifaceNumAsNumber = map[string]any{
74 "k1": Number("1"),
75 "k2": "s",
76 "k3": []any{Number("1"), Number("2.0"), Number("3e-3")},
77 "k4": map[string]any{"kk1": "s", "kk2": Number("2")},
78 }
79
80 type tx struct {
81 x int
82 }
83
84 type u8 uint8
85
86 // A type that can unmarshal itself.
87
88 type unmarshaler struct {
89 T bool
90 }
91
92 func (u *unmarshaler) UnmarshalJSON(b []byte) error {
93 *u = unmarshaler{true} // All we need to see that UnmarshalJSON is called.
94 return nil
95 }
96
97 type ustruct struct {
98 M unmarshaler
99 }
100
101 type unmarshalerText struct {
102 A, B string
103 }
104
105 // needed for re-marshaling tests
106 func (u unmarshalerText) MarshalText() ([]byte, error) {
107 return []byte(u.A + ":" + u.B), nil
108 }
109
110 func (u *unmarshalerText) UnmarshalText(b []byte) error {
111 pos := bytes.IndexByte(b, ':')
112 if pos == -1 {
113 return errors.New("missing separator")
114 }
115 u.A, u.B = string(b[:pos]), string(b[pos+1:])
116 return nil
117 }
118
119 var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil)
120
121 type ustructText struct {
122 M unmarshalerText
123 }
124
125 // u8marshal is an integer type that can marshal/unmarshal itself.
126 type u8marshal uint8
127
128 func (u8 u8marshal) MarshalText() ([]byte, error) {
129 return []byte(fmt.Sprintf("u%d", u8)), nil
130 }
131
132 var errMissingU8Prefix = errors.New("missing 'u' prefix")
133
134 func (u8 *u8marshal) UnmarshalText(b []byte) error {
135 if !bytes.HasPrefix(b, []byte{'u'}) {
136 return errMissingU8Prefix
137 }
138 n, err := strconv.Atoi(string(b[1:]))
139 if err != nil {
140 return err
141 }
142 *u8 = u8marshal(n)
143 return nil
144 }
145
146 var _ encoding.TextUnmarshaler = (*u8marshal)(nil)
147
148 var (
149 um0, um1 unmarshaler // target2 of unmarshaling
150 ump = &um1
151 umtrue = unmarshaler{true}
152 umslice = []unmarshaler{{true}}
153 umslicep = new([]unmarshaler)
154 umstruct = ustruct{unmarshaler{true}}
155
156 um0T, um1T unmarshalerText // target2 of unmarshaling
157 umpType = &um1T
158 umtrueXY = unmarshalerText{"x", "y"}
159 umsliceXY = []unmarshalerText{{"x", "y"}}
160 umslicepType = new([]unmarshalerText)
161 umstructType = new(ustructText)
162 umstructXY = ustructText{unmarshalerText{"x", "y"}}
163
164 ummapType = map[unmarshalerText]bool{}
165 ummapXY = map[unmarshalerText]bool{{"x", "y"}: true}
166 )
167
168 // Test data structures for anonymous fields.
169
170 type Point struct {
171 Z int
172 }
173
174 type Top struct {
175 Level0 int
176 Embed0
177 *Embed0a
178 *Embed0b `json:"e,omitempty"` // treated as named
179 Embed0c `json:"-"` // ignored
180 Loop
181 Embed0p // has Point with X, Y, used
182 Embed0q // has Point with Z, used
183 embed // contains exported field
184 }
185
186 type Embed0 struct {
187 Level1a int // overridden by Embed0a's Level1a with json tag
188 Level1b int // used because Embed0a's Level1b is renamed
189 Level1c int // used because Embed0a's Level1c is ignored
190 Level1d int // annihilated by Embed0a's Level1d
191 Level1e int `json:"x"` // annihilated by Embed0a.Level1e
192 }
193
194 type Embed0a struct {
195 Level1a int `json:"Level1a,omitempty"`
196 Level1b int `json:"LEVEL1B,omitempty"`
197 Level1c int `json:"-"`
198 Level1d int // annihilated by Embed0's Level1d
199 Level1f int `json:"x"` // annihilated by Embed0's Level1e
200 }
201
202 type Embed0b Embed0
203
204 type Embed0c Embed0
205
206 type Embed0p struct {
207 image.Point
208 }
209
210 type Embed0q struct {
211 Point
212 }
213
214 type embed struct {
215 Q int
216 }
217
218 type Loop struct {
219 Loop1 int `json:",omitempty"`
220 Loop2 int `json:",omitempty"`
221 *Loop
222 }
223
224 // From reflect test:
225 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
226 type S5 struct {
227 S6
228 S7
229 S8
230 }
231
232 type S6 struct {
233 X int
234 }
235
236 type S7 S6
237
238 type S8 struct {
239 S9
240 }
241
242 type S9 struct {
243 X int
244 Y int
245 }
246
247 // From reflect test:
248 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
249 type S10 struct {
250 S11
251 S12
252 S13
253 }
254
255 type S11 struct {
256 S6
257 }
258
259 type S12 struct {
260 S6
261 }
262
263 type S13 struct {
264 S8
265 }
266
267 type Ambig struct {
268 // Given "hello", the first match should win.
269 First int `json:"HELLO"`
270 Second int `json:"Hello"`
271 }
272
273 type XYZ struct {
274 X any
275 Y any
276 Z any
277 }
278
279 type unexportedWithMethods struct{}
280
281 func (unexportedWithMethods) F() {}
282
283 func sliceAddr(x []int) *[]int { return &x }
284 func mapAddr(x map[string]int) *map[string]int { return &x }
285
286 type byteWithMarshalJSON byte
287
288 func (b byteWithMarshalJSON) MarshalJSON() ([]byte, error) {
289 return []byte(fmt.Sprintf(`"Z%.2x"`, byte(b))), nil
290 }
291
292 func (b *byteWithMarshalJSON) UnmarshalJSON(data []byte) error {
293 if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' {
294 return fmt.Errorf("bad quoted string")
295 }
296 i, err := strconv.ParseInt(string(data[2:4]), 16, 8)
297 if err != nil {
298 return fmt.Errorf("bad hex")
299 }
300 *b = byteWithMarshalJSON(i)
301 return nil
302 }
303
304 type byteWithPtrMarshalJSON byte
305
306 func (b *byteWithPtrMarshalJSON) MarshalJSON() ([]byte, error) {
307 return byteWithMarshalJSON(*b).MarshalJSON()
308 }
309
310 func (b *byteWithPtrMarshalJSON) UnmarshalJSON(data []byte) error {
311 return (*byteWithMarshalJSON)(b).UnmarshalJSON(data)
312 }
313
314 type byteWithMarshalText byte
315
316 func (b byteWithMarshalText) MarshalText() ([]byte, error) {
317 return []byte(fmt.Sprintf(`Z%.2x`, byte(b))), nil
318 }
319
320 func (b *byteWithMarshalText) UnmarshalText(data []byte) error {
321 if len(data) != 3 || data[0] != 'Z' {
322 return fmt.Errorf("bad quoted string")
323 }
324 i, err := strconv.ParseInt(string(data[1:3]), 16, 8)
325 if err != nil {
326 return fmt.Errorf("bad hex")
327 }
328 *b = byteWithMarshalText(i)
329 return nil
330 }
331
332 type byteWithPtrMarshalText byte
333
334 func (b *byteWithPtrMarshalText) MarshalText() ([]byte, error) {
335 return byteWithMarshalText(*b).MarshalText()
336 }
337
338 func (b *byteWithPtrMarshalText) UnmarshalText(data []byte) error {
339 return (*byteWithMarshalText)(b).UnmarshalText(data)
340 }
341
342 type intWithMarshalJSON int
343
344 func (b intWithMarshalJSON) MarshalJSON() ([]byte, error) {
345 return []byte(fmt.Sprintf(`"Z%.2x"`, int(b))), nil
346 }
347
348 func (b *intWithMarshalJSON) UnmarshalJSON(data []byte) error {
349 if len(data) != 5 || data[0] != '"' || data[1] != 'Z' || data[4] != '"' {
350 return fmt.Errorf("bad quoted string")
351 }
352 i, err := strconv.ParseInt(string(data[2:4]), 16, 8)
353 if err != nil {
354 return fmt.Errorf("bad hex")
355 }
356 *b = intWithMarshalJSON(i)
357 return nil
358 }
359
360 type intWithPtrMarshalJSON int
361
362 func (b *intWithPtrMarshalJSON) MarshalJSON() ([]byte, error) {
363 return intWithMarshalJSON(*b).MarshalJSON()
364 }
365
366 func (b *intWithPtrMarshalJSON) UnmarshalJSON(data []byte) error {
367 return (*intWithMarshalJSON)(b).UnmarshalJSON(data)
368 }
369
370 type intWithMarshalText int
371
372 func (b intWithMarshalText) MarshalText() ([]byte, error) {
373 return []byte(fmt.Sprintf(`Z%.2x`, int(b))), nil
374 }
375
376 func (b *intWithMarshalText) UnmarshalText(data []byte) error {
377 if len(data) != 3 || data[0] != 'Z' {
378 return fmt.Errorf("bad quoted string")
379 }
380 i, err := strconv.ParseInt(string(data[1:3]), 16, 8)
381 if err != nil {
382 return fmt.Errorf("bad hex")
383 }
384 *b = intWithMarshalText(i)
385 return nil
386 }
387
388 type intWithPtrMarshalText int
389
390 func (b *intWithPtrMarshalText) MarshalText() ([]byte, error) {
391 return intWithMarshalText(*b).MarshalText()
392 }
393
394 func (b *intWithPtrMarshalText) UnmarshalText(data []byte) error {
395 return (*intWithMarshalText)(b).UnmarshalText(data)
396 }
397
398 type mapStringToStringData struct {
399 Data map[string]string `json:"data"`
400 }
401
402 type unmarshalTest struct {
403 in string
404 ptr any
405 out any
406 err error
407 useNumber bool
408 golden bool
409 disallowUnknownFields bool
410 }
411
412 type B struct {
413 B bool `json:",string"`
414 }
415
416 var unmarshalTests = []unmarshalTest{
417 // basic types
418 {in: `true`, ptr: new(bool), out: true},
419 {in: `1`, ptr: new(int), out: 1},
420 {in: `1.2`, ptr: new(float64), out: 1.2},
421 {in: `-5`, ptr: new(int16), out: int16(-5)},
422 {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true},
423 {in: `2`, ptr: new(Number), out: Number("2")},
424 {in: `2`, ptr: new(any), out: float64(2.0)},
425 {in: `2`, ptr: new(any), out: Number("2"), useNumber: true},
426 {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},
427 {in: `"http:\/\/"`, ptr: new(string), out: "http://"},
428 {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},
429 //TODO
430 //{in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
431 {in: "null", ptr: new(any), out: nil},
432 {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{Value: "array", Type: reflect.TypeOf(""), Offset: 7, Struct: "T", Field: "X"}},
433 {in: `{"X": 23}`, ptr: new(T), out: T{}, err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 8, Struct: "T", Field: "X"}},
434 {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
435 {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
436 {in: `{"x": 1}`, ptr: new(tx), err: fmt.Errorf("json: unknown field \"x\""), disallowUnknownFields: true},
437 {in: `{"S": 23}`, ptr: new(W), out: W{}, err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(SS("")), Offset: 0, Struct: "W", Field: "S"}},
438 {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
439 {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
440 {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsFloat64},
441 {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsNumber, useNumber: true},
442
443 // raw values with whitespace
444 {in: "\n true ", ptr: new(bool), out: true},
445 {in: "\t 1 ", ptr: new(int), out: 1},
446 {in: "\r 1.2 ", ptr: new(float64), out: 1.2},
447 {in: "\t -5 \n", ptr: new(int16), out: int16(-5)},
448 {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"},
449
450 // Z has a "-" tag.
451 {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}},
452 {in: `{"Y": 1, "Z": 2}`, ptr: new(T), err: fmt.Errorf("json: unknown field \"Z\""), disallowUnknownFields: true},
453
454 {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}},
455 {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), err: fmt.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields: true},
456 {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}},
457 {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}},
458 {in: `{"alphabet": "xyz"}`, ptr: new(U), err: fmt.Errorf("json: unknown field \"alphabet\""), disallowUnknownFields: true},
459
460 // syntax errors
461 {in: `{"X": "foo", "Y"}`, err: &testSyntaxError{"invalid character '}' after object key", 17}},
462 {in: `[1, 2, 3+]`, err: &testSyntaxError{"invalid character '+' after array element", 9}},
463 {in: `{"X":12x}`, err: &testSyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true},
464 {in: `[2, 3`, err: &testSyntaxError{msg: "unexpected end of JSON input", Offset: 5}},
465
466 // raw value errors
467 {in: "\x01 42", err: &testSyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
468 {in: " 42 \x01", err: &testSyntaxError{"invalid character '\\x01' after top-level value", 5}},
469 {in: "\x01 true", err: &testSyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
470 {in: " false \x01", err: &testSyntaxError{"invalid character '\\x01' after top-level value", 8}},
471 {in: "\x01 1.2", err: &testSyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
472 {in: " 3.4 \x01", err: &testSyntaxError{"invalid character '\\x01' after top-level value", 6}},
473 {in: "\x01 \"string\"", err: &testSyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
474 {in: " \"string\" \x01", err: &testSyntaxError{"invalid character '\\x01' after top-level value", 11}},
475
476 // array tests
477 {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}},
478 {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}},
479 {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}},
480 {in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")},
481
482 // empty array to interface test
483 {in: `[]`, ptr: new([]any), out: []any{}},
484 {in: `null`, ptr: new([]any), out: []any(nil)},
485 {in: `{"T":[]}`, ptr: new(map[string]any), out: map[string]any{"T": []any{}}},
486 {in: `{"T":null}`, ptr: new(map[string]any), out: map[string]any{"T": any(nil)}},
487
488 // composite tests
489 {in: allValueIndent, ptr: new(All), out: allValue},
490 {in: allValueCompact, ptr: new(All), out: allValue},
491 {in: allValueIndent, ptr: new(*All), out: &allValue},
492 {in: allValueCompact, ptr: new(*All), out: &allValue},
493 {in: pallValueIndent, ptr: new(All), out: pallValue},
494 {in: pallValueCompact, ptr: new(All), out: pallValue},
495 {in: pallValueIndent, ptr: new(*All), out: &pallValue},
496 {in: pallValueCompact, ptr: new(*All), out: &pallValue},
497
498 // unmarshal interface test
499 {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called
500 {in: `{"T":false}`, ptr: &ump, out: &umtrue},
501 {in: `[{"T":false}]`, ptr: &umslice, out: umslice},
502 {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice},
503 {in: `{"M":{"T":"x:y"}}`, ptr: &umstruct, out: umstruct},
504
505 // UnmarshalText interface test
506 {in: `"x:y"`, ptr: &um0T, out: umtrueXY},
507 {in: `"x:y"`, ptr: &umpType, out: &umtrueXY},
508 {in: `["x:y"]`, ptr: &umsliceXY, out: umsliceXY},
509 {in: `["x:y"]`, ptr: &umslicepType, out: &umsliceXY},
510 {in: `{"M":"x:y"}`, ptr: umstructType, out: umstructXY},
511
512 // integer-keyed map test
513 {
514 in: `{"-1":"a","0":"b","1":"c"}`,
515 ptr: new(map[int]string),
516 out: map[int]string{-1: "a", 0: "b", 1: "c"},
517 },
518 {
519 in: `{"0":"a","10":"c","9":"b"}`,
520 ptr: new(map[u8]string),
521 out: map[u8]string{0: "a", 9: "b", 10: "c"},
522 },
523 {
524 in: `{"-9223372036854775808":"min","9223372036854775807":"max"}`,
525 ptr: new(map[int64]string),
526 out: map[int64]string{math.MinInt64: "min", math.MaxInt64: "max"},
527 },
528 {
529 in: `{"18446744073709551615":"max"}`,
530 ptr: new(map[uint64]string),
531 out: map[uint64]string{math.MaxUint64: "max"},
532 },
533 {
534 in: `{"0":false,"10":true}`,
535 ptr: new(map[uintptr]bool),
536 out: map[uintptr]bool{0: false, 10: true},
537 },
538
539 // Check that MarshalText and UnmarshalText take precedence
540 // over default integer handling in map keys.
541 {
542 in: `{"u2":4}`,
543 ptr: new(map[u8marshal]int),
544 out: map[u8marshal]int{2: 4},
545 },
546 {
547 in: `{"2":4}`,
548 ptr: new(map[u8marshal]int),
549 err: errMissingU8Prefix,
550 },
551
552 // integer-keyed map errors
553 {
554 in: `{"abc":"abc"}`,
555 ptr: new(map[int]string),
556 err: &UnmarshalTypeError{Value: "number abc", Type: reflect.TypeOf(0), Offset: 2},
557 },
558 {
559 in: `{"256":"abc"}`,
560 ptr: new(map[uint8]string),
561 err: &UnmarshalTypeError{Value: "number 256", Type: reflect.TypeOf(uint8(0)), Offset: 2},
562 },
563 {
564 in: `{"128":"abc"}`,
565 ptr: new(map[int8]string),
566 err: &UnmarshalTypeError{Value: "number 128", Type: reflect.TypeOf(int8(0)), Offset: 2},
567 },
568 {
569 in: `{"-1":"abc"}`,
570 ptr: new(map[uint8]string),
571 err: &UnmarshalTypeError{Value: "number -1", Type: reflect.TypeOf(uint8(0)), Offset: 2},
572 },
573 {
574 in: `{"F":{"a":2,"3":4}}`,
575 ptr: new(map[string]map[int]int),
576 err: &UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(int(0)), Offset: 7},
577 },
578 {
579 in: `{"F":{"a":2,"3":4}}`,
580 ptr: new(map[string]map[uint]int),
581 err: &UnmarshalTypeError{Value: "number a", Type: reflect.TypeOf(uint(0)), Offset: 7},
582 },
583
584 // Map keys can be encoding.TextUnmarshalers.
585 {in: `{"x:y":true}`, ptr: &ummapType, out: ummapXY},
586 // If multiple values for the same key exists, only the most recent value is used.
587 {in: `{"x:y":false,"x:y":true}`, ptr: &ummapType, out: ummapXY},
588
589 // Overwriting of data.
590 // This is different from package xml, but it's what we've always done.
591 // Now documented and tested.
592 {in: `[2]`, ptr: sliceAddr([]int{1}), out: []int{2}},
593 {in: `{"key": 2}`, ptr: mapAddr(map[string]int{"old": 0, "key": 1}), out: map[string]int{"key": 2}},
594
595 {
596 in: `{
597 "Level0": 1,
598 "Level1b": 2,
599 "Level1c": 3,
600 "x": 4,
601 "Level1a": 5,
602 "LEVEL1B": 6,
603 "e": {
604 "Level1a": 8,
605 "Level1b": 9,
606 "Level1c": 10,
607 "Level1d": 11,
608 "x": 12
609 },
610 "Loop1": 13,
611 "Loop2": 14,
612 "X": 15,
613 "Y": 16,
614 "Z": 17,
615 "Q": 18
616 }`,
617 ptr: new(Top),
618 out: Top{
619 Level0: 1,
620 Embed0: Embed0{
621 Level1b: 2,
622 Level1c: 3,
623 },
624 Embed0a: &Embed0a{
625 Level1a: 5,
626 Level1b: 6,
627 },
628 Embed0b: &Embed0b{
629 Level1a: 8,
630 Level1b: 9,
631 Level1c: 10,
632 Level1d: 11,
633 Level1e: 12,
634 },
635 Loop: Loop{
636 Loop1: 13,
637 Loop2: 14,
638 },
639 Embed0p: Embed0p{
640 Point: image.Point{X: 15, Y: 16},
641 },
642 Embed0q: Embed0q{
643 Point: Point{Z: 17},
644 },
645 embed: embed{
646 Q: 18,
647 },
648 },
649 },
650 {
651 in: `{"hello": 1}`,
652 ptr: new(Ambig),
653 out: Ambig{First: 1},
654 },
655 {
656 in: `{"X": 1,"Y":2}`,
657 ptr: new(S5),
658 out: S5{S8: S8{S9: S9{Y: 2}}},
659 },
660 {
661 in: `{"X": 1,"Y":2}`,
662 ptr: new(S5),
663 err: fmt.Errorf("json: unknown field \"X\""),
664 disallowUnknownFields: true,
665 },
666 {
667 in: `{"X": 1,"Y":2}`,
668 ptr: new(S10),
669 out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}},
670 },
671 {
672 in: `{"X": 1,"Y":2}`,
673 ptr: new(S10),
674 err: fmt.Errorf("json: unknown field \"X\""),
675 disallowUnknownFields: true,
676 },
677
678 // invalid UTF-8 is coerced to valid UTF-8.
679 {
680 in: "\"hello\xffworld\"",
681 ptr: new(string),
682 out: "hello\ufffdworld",
683 },
684 {
685 in: "\"hello\xc2\xc2world\"",
686 ptr: new(string),
687 out: "hello\ufffd\ufffdworld",
688 },
689 {
690 in: "\"hello\xc2\xffworld\"",
691 ptr: new(string),
692 out: "hello\ufffd\ufffdworld",
693 },
694 {
695 in: "\"hello\\ud800world\"",
696 ptr: new(string),
697 out: "hello\ufffdworld",
698 },
699 {
700 in: "\"hello\\ud800\\ud800world\"",
701 ptr: new(string),
702 out: "hello\ufffd\ufffdworld",
703 },
704 {
705 in: "\"hello\\ud800\\ud800world\"",
706 ptr: new(string),
707 out: "hello\ufffd\ufffdworld",
708 },
709 {
710 in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"",
711 ptr: new(string),
712 out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld",
713 },
714
715 // Used to be issue 8305, but time.Time implements encoding.TextUnmarshaler so this works now.
716 {
717 in: `{"2009-11-10T23:00:00Z": "hello world"}`,
718 ptr: &map[time.Time]string{},
719 out: map[time.Time]string{time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC): "hello world"},
720 },
721
722 // issue 8305
723 {
724 in: `{"2009-11-10T23:00:00Z": "hello world"}`,
725 ptr: &map[Point]string{},
726 err: &UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(map[Point]string{}), Offset: 1},
727 },
728 {
729 in: `{"asdf": "hello world"}`,
730 ptr: &map[unmarshaler]string{},
731 err: &UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(map[unmarshaler]string{}), Offset: 1},
732 },
733
734 // related to issue 13783.
735 // Go 1.7 changed marshaling a slice of typed byte to use the methods on the byte type,
736 // similar to marshaling a slice of typed int.
737 // These tests check that, assuming the byte type also has valid decoding methods,
738 // either the old base64 string encoding or the new per-element encoding can be
739 // successfully unmarshaled. The custom unmarshalers were accessible in earlier
740 // versions of Go, even though the custom marshaler was not.
741 {
742 in: `"AQID"`,
743 ptr: new([]byteWithMarshalJSON),
744 out: []byteWithMarshalJSON{1, 2, 3},
745 },
746 {
747 in: `["Z01","Z02","Z03"]`,
748 ptr: new([]byteWithMarshalJSON),
749 out: []byteWithMarshalJSON{1, 2, 3},
750 golden: true,
751 },
752 {
753 in: `"AQID"`,
754 ptr: new([]byteWithMarshalText),
755 out: []byteWithMarshalText{1, 2, 3},
756 },
757 {
758 in: `["Z01","Z02","Z03"]`,
759 ptr: new([]byteWithMarshalText),
760 out: []byteWithMarshalText{1, 2, 3},
761 golden: true,
762 },
763 {
764 in: `"AQID"`,
765 ptr: new([]byteWithPtrMarshalJSON),
766 out: []byteWithPtrMarshalJSON{1, 2, 3},
767 },
768 {
769 in: `["Z01","Z02","Z03"]`,
770 ptr: new([]byteWithPtrMarshalJSON),
771 out: []byteWithPtrMarshalJSON{1, 2, 3},
772 golden: true,
773 },
774 {
775 in: `"AQID"`,
776 ptr: new([]byteWithPtrMarshalText),
777 out: []byteWithPtrMarshalText{1, 2, 3},
778 },
779 {
780 in: `["Z01","Z02","Z03"]`,
781 ptr: new([]byteWithPtrMarshalText),
782 out: []byteWithPtrMarshalText{1, 2, 3},
783 golden: true,
784 },
785
786 // ints work with the marshaler but not the base64 []byte case
787 {
788 in: `["Z01","Z02","Z03"]`,
789 ptr: new([]intWithMarshalJSON),
790 out: []intWithMarshalJSON{1, 2, 3},
791 golden: true,
792 },
793 {
794 in: `["Z01","Z02","Z03"]`,
795 ptr: new([]intWithMarshalText),
796 out: []intWithMarshalText{1, 2, 3},
797 golden: true,
798 },
799 {
800 in: `["Z01","Z02","Z03"]`,
801 ptr: new([]intWithPtrMarshalJSON),
802 out: []intWithPtrMarshalJSON{1, 2, 3},
803 golden: true,
804 },
805 {
806 in: `["Z01","Z02","Z03"]`,
807 ptr: new([]intWithPtrMarshalText),
808 out: []intWithPtrMarshalText{1, 2, 3},
809 golden: true,
810 },
811
812 {in: `0.000001`, ptr: new(float64), out: 0.000001, golden: true},
813 {in: `1e-7`, ptr: new(float64), out: 1e-7, golden: true},
814 {in: `100000000000000000000`, ptr: new(float64), out: 100000000000000000000.0, golden: true},
815 {in: `1e+21`, ptr: new(float64), out: 1e21, golden: true},
816 {in: `-0.000001`, ptr: new(float64), out: -0.000001, golden: true},
817 {in: `-1e-7`, ptr: new(float64), out: -1e-7, golden: true},
818 {in: `-100000000000000000000`, ptr: new(float64), out: -100000000000000000000.0, golden: true},
819 {in: `-1e+21`, ptr: new(float64), out: -1e21, golden: true},
820 {in: `999999999999999900000`, ptr: new(float64), out: 999999999999999900000.0, golden: true},
821 {in: `9007199254740992`, ptr: new(float64), out: 9007199254740992.0, golden: true},
822 {in: `9007199254740993`, ptr: new(float64), out: 9007199254740992.0, golden: false},
823
824 {
825 in: `{"V": {"F2": "hello"}}`,
826 ptr: new(VOuter),
827 err: &UnmarshalTypeError{
828 Value: "string",
829 Struct: "V",
830 Field: "V.F2",
831 Type: reflect.TypeOf(int32(0)),
832 Offset: 20,
833 },
834 },
835 {
836 in: `{"V": {"F4": {}, "F2": "hello"}}`,
837 ptr: new(VOuter),
838 err: &UnmarshalTypeError{
839 Value: "string",
840 Struct: "V",
841 Field: "V.F2",
842 Type: reflect.TypeOf(int32(0)),
843 Offset: 30,
844 },
845 },
846
847 // issue 15146.
848 // invalid inputs in wrongStringTests below.
849 {in: `{"B":"true"}`, ptr: new(B), out: B{true}, golden: true},
850 {in: `{"B":"false"}`, ptr: new(B), out: B{false}, golden: true},
851 {in: `{"B": "maybe"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "maybe" into bool`)},
852 {in: `{"B": "tru"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "tru" into bool`)},
853 {in: `{"B": "False"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "False" into bool`)},
854 {in: `{"B": "null"}`, ptr: new(B), out: B{false}},
855 {in: `{"B": "nul"}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal "nul" into bool`)},
856 {in: `{"B": [2, 3]}`, ptr: new(B), err: errors.New(`json: invalid use of ,string struct tag, trying to unmarshal unquoted value into bool`)},
857
858 // additional tests for disallowUnknownFields
859 {
860 in: `{
861 "Level0": 1,
862 "Level1b": 2,
863 "Level1c": 3,
864 "x": 4,
865 "Level1a": 5,
866 "LEVEL1B": 6,
867 "e": {
868 "Level1a": 8,
869 "Level1b": 9,
870 "Level1c": 10,
871 "Level1d": 11,
872 "x": 12
873 },
874 "Loop1": 13,
875 "Loop2": 14,
876 "X": 15,
877 "Y": 16,
878 "Z": 17,
879 "Q": 18,
880 "extra": true
881 }`,
882 ptr: new(Top),
883 err: fmt.Errorf("json: unknown field \"extra\""),
884 disallowUnknownFields: true,
885 },
886 {
887 in: `{
888 "Level0": 1,
889 "Level1b": 2,
890 "Level1c": 3,
891 "x": 4,
892 "Level1a": 5,
893 "LEVEL1B": 6,
894 "e": {
895 "Level1a": 8,
896 "Level1b": 9,
897 "Level1c": 10,
898 "Level1d": 11,
899 "x": 12,
900 "extra": null
901 },
902 "Loop1": 13,
903 "Loop2": 14,
904 "X": 15,
905 "Y": 16,
906 "Z": 17,
907 "Q": 18
908 }`,
909 ptr: new(Top),
910 err: fmt.Errorf("json: unknown field \"extra\""),
911 disallowUnknownFields: true,
912 },
913 // issue 26444
914 // UnmarshalTypeError without field & struct values
915 {
916 in: `{"data":{"test1": "bob", "test2": 123}}`,
917 ptr: new(mapStringToStringData),
918 err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 37, Struct: "mapStringToStringData", Field: "data"},
919 },
920 {
921 in: `{"data":{"test1": 123, "test2": "bob"}}`,
922 ptr: new(mapStringToStringData),
923 err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 21, Struct: "mapStringToStringData", Field: "data"},
924 },
925
926 // trying to decode JSON arrays or objects via TextUnmarshaler
927 {
928 in: `[1, 2, 3]`,
929 ptr: new(MustNotUnmarshalText),
930 err: &UnmarshalTypeError{Value: "array", Type: reflect.TypeOf(&MustNotUnmarshalText{}), Offset: 1},
931 },
932 {
933 in: `{"foo": "bar"}`,
934 ptr: new(MustNotUnmarshalText),
935 err: &UnmarshalTypeError{Value: "object", Type: reflect.TypeOf(&MustNotUnmarshalText{}), Offset: 1},
936 },
937 // #22369
938 {
939 in: `{"PP": {"T": {"Y": "bad-type"}}}`,
940 ptr: new(P),
941 err: &UnmarshalTypeError{
942 Value: "string",
943 Struct: "T",
944 Field: "PP.T.Y",
945 Type: reflect.TypeOf(int(0)),
946 Offset: 29,
947 },
948 },
949 {
950 in: `{"Ts": [{"Y": 1}, {"Y": 2}, {"Y": "bad-type"}]}`,
951 ptr: new(PP),
952 err: &UnmarshalTypeError{
953 Value: "string",
954 Struct: "T",
955 Field: "Ts.Y",
956 Type: reflect.TypeOf(int(0)),
957 Offset: 29,
958 },
959 },
960 }
961
962 func TestMarshal(t *testing.T) {
963 b, err := Marshal(allValue)
964 if err != nil {
965 t.Fatalf("Marshal allValue: %v", err)
966 }
967 if string(b) != allValueCompact {
968 t.Errorf("Marshal allValueCompact")
969 diff(t, b, []byte(allValueCompact))
970 return
971 }
972
973 b, err = Marshal(pallValue)
974 if err != nil {
975 t.Fatalf("Marshal pallValue: %v", err)
976 }
977 if string(b) != pallValueCompact {
978 t.Errorf("Marshal pallValueCompact")
979 diff(t, b, []byte(pallValueCompact))
980 return
981 }
982 }
983
984 var badUTF8 = []struct {
985 in, out string
986 }{
987 {"hello\xffworld", `"hello\ufffdworld"`},
988 {"", `""`},
989 {"\xff", `"\ufffd"`},
990 {"\xff\xff", `"\ufffd\ufffd"`},
991 {"a\xffb", `"a\ufffdb"`},
992 {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`},
993 }
994
995 func TestMarshalBadUTF8(t *testing.T) {
996 for _, tt := range badUTF8 {
997 b, err := Marshal(tt.in)
998 if string(b) != tt.out || err != nil {
999 t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out)
1000 }
1001 }
1002 }
1003
1004 func TestMarshalNumberZeroVal(t *testing.T) {
1005 var n Number
1006 out, err := Marshal(n)
1007 if err != nil {
1008 t.Fatal(err)
1009 }
1010 outStr := string(out)
1011 if outStr != "0" {
1012 t.Fatalf("Invalid zero val for Number: %q", outStr)
1013 }
1014 }
1015
1016 func TestMarshalEmbeds(t *testing.T) {
•1017 if runtime.GOARCH == "386" || runtime.GOARCH == "arm" {
1018 t.Skipf("Marshal sorting order differs on %s.", runtime.GOARCH)
1019 }
1020 top := &Top{
1021 Level0: 1,
1022 Embed0: Embed0{
1023 Level1b: 2,
1024 Level1c: 3,
1025 },
1026 Embed0a: &Embed0a{
1027 Level1a: 5,
1028 Level1b: 6,
1029 },
1030 Embed0b: &Embed0b{
1031 Level1a: 8,
1032 Level1b: 9,
1033 Level1c: 10,
1034 Level1d: 11,
1035 Level1e: 12,
1036 },
1037 Loop: Loop{
1038 Loop1: 13,
1039 Loop2: 14,
1040 },
1041 Embed0p: Embed0p{
1042 Point: image.Point{X: 15, Y: 16},
1043 },
1044 Embed0q: Embed0q{
1045 Point: Point{Z: 17},
1046 },
1047 embed: embed{
1048 Q: 18,
1049 },
1050 }
1051 b, err := Marshal(top)
1052 if err != nil {
1053 t.Fatal(err)
1054 }
1055 want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}"
1056 if string(b) != want {
1057 t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want)
1058 }
1059 }
1060
1061 func equalError(a, b error) bool {
1062 if a == nil {
1063 return b == nil
1064 }
1065 if b == nil {
1066 return a == nil
1067 }
1068 return a.Error() == b.Error()
1069 }
1070
1071 func TestUnmarshal(t *testing.T) {
1072 for i, tt := range unmarshalTests {
1073 var scan scanner
1074 in := []byte(tt.in)
1075 if err := checkValid(in, &scan); err != nil {
1076 if !equalError(err, tt.err) {
1077 t.Errorf("#%d: checkValid: %#v", i, err)
1078 continue
1079 }
1080 }
1081 if tt.ptr == nil {
1082 continue
1083 }
1084
1085 // v = new(right-type)
1086 v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
1087 dec := NewDecoder(bytes.NewReader(in))
1088 if tt.useNumber {
1089 dec.UseNumber()
1090 }
1091 if tt.disallowUnknownFields {
1092 dec.DisallowUnknownFields()
1093 }
1094 err := dec.Decode(v.Interface())
1095 assertErrorPresence(t, tt.err, err, "testUnmarshal", i, tt.in)
1096 if err != nil {
1097 continue
1098 }
1099 if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
1100 t.Errorf("#%d: mismatch\n%v\nhave: %#+v\nwant: %#+v", i, tt.in, v.Elem().Interface(), tt.out)
1101 data, _ := Marshal(v.Elem().Interface())
1102 println(string(data))
1103 data, _ = Marshal(tt.out)
1104 println(string(data))
1105 continue
1106 }
1107
1108 // Check round trip also decodes correctly.
1109 if tt.err == nil {
1110 enc, err := Marshal(v.Interface())
1111 if err != nil {
1112 t.Errorf("#%d: error re-marshaling: %v", i, err)
1113 continue
1114 }
1115 if tt.golden && !bytes.Equal(enc, in) {
1116 t.Errorf("#%d: remarshal mismatch:\nhave: %s\nwant: %s", i, enc, in)
1117 }
1118 vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
1119 dec = NewDecoder(bytes.NewReader(enc))
1120 if tt.useNumber {
1121 dec.UseNumber()
1122 }
1123 if err := dec.Decode(vv.Interface()); err != nil {
1124 t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err)
1125 continue
1126 }
1127 if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
1128 t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
1129 t.Errorf(" In: %q", strings.Map(noSpace, string(in)))
1130 t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc)))
1131 continue
1132 }
1133 }
1134 }
1135 }
1136
1137 func TestUnmarshalMarshal(t *testing.T) {
•1138 if runtime.GOARCH == "s390x" {
1139 t.Skipf("Test does not work correctly on %s.", runtime.GOARCH)
1140 }
1141 initBig()
1142 var v any
1143 if err := Unmarshal(jsonBig, &v); err != nil {
1144 t.Fatalf("Unmarshal: %v", err)
1145 }
1146 b, err := Marshal(v)
1147 if err != nil {
1148 t.Fatalf("Marshal: %v", err)
1149 }
1150 if !bytes.Equal(jsonBig, b) {
1151 t.Errorf("Marshal jsonBig")
1152 diff(t, b, jsonBig)
1153 return
1154 }
1155 }
1156
1157 var numberTests = []struct {
1158 in string
1159 i int64
1160 intErr string
1161 f float64
1162 floatErr string
1163 }{
1164 {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1},
1165 {in: "-12", i: -12, f: -12.0},
1166 {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
1167 }
1168
1169 // Independent of Decode, basic coverage of the accessors in Number
1170 func TestNumberAccessors(t *testing.T) {
1171 for _, tt := range numberTests {
1172 n := Number(tt.in)
1173 if s := n.String(); s != tt.in {
1174 t.Errorf("Number(%q).String() is %q", tt.in, s)
1175 }
1176 if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i {
1177 t.Errorf("Number(%q).Int64() is %d", tt.in, i)
1178 } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) {
1179 t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err)
1180 }
1181 if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f {
1182 t.Errorf("Number(%q).Float64() is %g", tt.in, f)
1183 } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) {
1184 t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err)
1185 }
1186 }
1187 }
1188
1189 func TestLargeByteSlice(t *testing.T) {
1190 s0 := make([]byte, 2000)
1191 for i := range s0 {
1192 s0[i] = byte(i)
1193 }
1194 b, err := Marshal(s0)
1195 if err != nil {
1196 t.Fatalf("Marshal: %v", err)
1197 }
1198 var s1 []byte
1199 if err := Unmarshal(b, &s1); err != nil {
1200 t.Fatalf("Unmarshal: %v", err)
1201 }
1202 if !bytes.Equal(s0, s1) {
1203 t.Errorf("Marshal large byte slice")
1204 diff(t, s0, s1)
1205 }
1206 }
1207
1208 type Xint struct {
1209 X int
1210 }
1211
1212 func TestUnmarshalInterface(t *testing.T) {
1213 var xint Xint
1214 var i any = &xint
1215 if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil {
1216 t.Fatalf("Unmarshal: %v", err)
1217 }
1218 if xint.X != 1 {
1219 t.Fatalf("Did not write to xint")
1220 }
1221 }
1222
1223 func TestUnmarshalPtrPtr(t *testing.T) {
1224 var xint Xint
1225 pxint := &xint
1226 if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil {
1227 t.Fatalf("Unmarshal: %v", err)
1228 }
1229 if xint.X != 1 {
1230 t.Fatalf("Did not write to xint")
1231 }
1232 }
1233
1234 func TestEscape(t *testing.T) {
1235 const input = `"foobar"<html>` + " [\u2028 \u2029]"
1236 const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"`
1237 b, err := Marshal(input)
1238 if err != nil {
1239 t.Fatalf("Marshal error: %v", err)
1240 }
1241 if s := string(b); s != expected {
1242 t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected)
1243 }
1244 }
1245
1246 // WrongString is a struct that's misusing the ,string modifier.
1247 type WrongString struct {
1248 Message string `json:"result,string"`
1249 }
1250
1251 type wrongStringTest struct {
1252 in, err string
1253 }
1254
1255 var wrongStringTests = []wrongStringTest{
1256 {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`},
1257 {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`},
1258 {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`},
1259 {`{"result":123}`, `json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string`},
1260 {`{"result":"\""}`, `json: invalid use of ,string struct tag, trying to unmarshal "\"" into string`},
1261 {`{"result":"\"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "\"foo" into string`},
1262 }
1263
1264 // If people misuse the ,string modifier, the error message should be
1265 // helpful, telling the user that they're doing it wrong.
1266 func TestErrorMessageFromMisusedString(t *testing.T) {
1267 for n, tt := range wrongStringTests {
1268 r := strings.NewReader(tt.in)
1269 var s WrongString
1270 err := NewDecoder(r).Decode(&s)
1271 assertErrorPresence(t, errors.New(tt.err), err, n)
1272 }
1273 }
1274
1275 func noSpace(c rune) rune {
1276 if isSpace(byte(c)) { // only used for ascii
1277 return -1
1278 }
1279 return c
1280 }
1281
1282 type All struct {
1283 Bool bool
1284 Int int
1285 Int8 int8
1286 Int16 int16
1287 Int32 int32
1288 Int64 int64
1289 Uint uint
1290 Uint8 uint8
1291 Uint16 uint16
1292 Uint32 uint32
1293 Uint64 uint64
1294 Uintptr uintptr
1295 Float32 float32
1296 Float64 float64
1297
1298 Foo string `json:"bar"`
1299 Foo2 string `json:"bar2,dummyopt"`
1300
1301 IntStr int64 `json:",string"`
1302 UintptrStr uintptr `json:",string"`
1303
1304 PBool *bool
1305 PInt *int
1306 PInt8 *int8
1307 PInt16 *int16
1308 PInt32 *int32
1309 PInt64 *int64
1310 PUint *uint
1311 PUint8 *uint8
1312 PUint16 *uint16
1313 PUint32 *uint32
1314 PUint64 *uint64
1315 PUintptr *uintptr
1316 PFloat32 *float32
1317 PFloat64 *float64
1318
1319 String string
1320 PString *string
1321
1322 Map map[string]Small
1323 MapP map[string]*Small
1324 PMap *map[string]Small
1325 PMapP *map[string]*Small
1326
1327 EmptyMap map[string]Small
1328 NilMap map[string]Small
1329
1330 Slice []Small
1331 SliceP []*Small
1332 PSlice *[]Small
1333 PSliceP *[]*Small
1334
1335 EmptySlice []Small
1336 NilSlice []Small
1337
1338 StringSlice []string
1339 ByteSlice []byte
1340
1341 Small Small
1342 PSmall *Small
1343 PPSmall **Small
1344
1345 Interface any
1346 PInterface *any
1347
1348 unexported int
1349 }
1350
1351 type Small struct {
1352 Tag string
1353 }
1354
1355 var allValue = All{
1356 Bool: true,
1357 Int: 2,
1358 Int8: 3,
1359 Int16: 4,
1360 Int32: 5,
1361 Int64: 6,
1362 Uint: 7,
1363 Uint8: 8,
1364 Uint16: 9,
1365 Uint32: 10,
1366 Uint64: 11,
1367 Uintptr: 12,
1368 Float32: 14.1,
1369 Float64: 15.1,
1370 Foo: "foo",
1371 Foo2: "foo2",
1372 IntStr: 42,
1373 UintptrStr: 44,
1374 String: "16",
1375 Map: map[string]Small{
1376 "17": {Tag: "tag17"},
1377 "18": {Tag: "tag18"},
1378 },
1379 MapP: map[string]*Small{
1380 "19": {Tag: "tag19"},
1381 "20": nil,
1382 },
1383 EmptyMap: map[string]Small{},
1384 Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}},
1385 SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}},
1386 EmptySlice: []Small{},
1387 StringSlice: []string{"str24", "str25", "str26"},
1388 ByteSlice: []byte{27, 28, 29},
1389 Small: Small{Tag: "tag30"},
1390 PSmall: &Small{Tag: "tag31"},
1391 Interface: 5.2,
1392 }
1393
1394 var pallValue = All{
1395 PBool: &allValue.Bool,
1396 PInt: &allValue.Int,
1397 PInt8: &allValue.Int8,
1398 PInt16: &allValue.Int16,
1399 PInt32: &allValue.Int32,
1400 PInt64: &allValue.Int64,
1401 PUint: &allValue.Uint,
1402 PUint8: &allValue.Uint8,
1403 PUint16: &allValue.Uint16,
1404 PUint32: &allValue.Uint32,
1405 PUint64: &allValue.Uint64,
1406 PUintptr: &allValue.Uintptr,
1407 PFloat32: &allValue.Float32,
1408 PFloat64: &allValue.Float64,
1409 PString: &allValue.String,
1410 PMap: &allValue.Map,
1411 PMapP: &allValue.MapP,
1412 PSlice: &allValue.Slice,
1413 PSliceP: &allValue.SliceP,
1414 PPSmall: &allValue.PSmall,
1415 PInterface: &allValue.Interface,
1416 }
1417
1418 var allValueIndent = `{
1419 "Bool": true,
1420 "Int": 2,
1421 "Int8": 3,
1422 "Int16": 4,
1423 "Int32": 5,
1424 "Int64": 6,
1425 "Uint": 7,
1426 "Uint8": 8,
1427 "Uint16": 9,
1428 "Uint32": 10,
1429 "Uint64": 11,
1430 "Uintptr": 12,
1431 "Float32": 14.1,
1432 "Float64": 15.1,
1433 "bar": "foo",
1434 "bar2": "foo2",
1435 "IntStr": "42",
1436 "UintptrStr": "44",
1437 "PBool": null,
1438 "PInt": null,
1439 "PInt8": null,
1440 "PInt16": null,
1441 "PInt32": null,
1442 "PInt64": null,
1443 "PUint": null,
1444 "PUint8": null,
1445 "PUint16": null,
1446 "PUint32": null,
1447 "PUint64": null,
1448 "PUintptr": null,
1449 "PFloat32": null,
1450 "PFloat64": null,
1451 "String": "16",
1452 "PString": null,
1453 "Map": {
1454 "17": {
1455 "Tag": "tag17"
1456 },
1457 "18": {
1458 "Tag": "tag18"
1459 }
1460 },
1461 "MapP": {
1462 "19": {
1463 "Tag": "tag19"
1464 },
1465 "20": null
1466 },
1467 "PMap": null,
1468 "PMapP": null,
1469 "EmptyMap": {},
1470 "NilMap": null,
1471 "Slice": [
1472 {
1473 "Tag": "tag20"
1474 },
1475 {
1476 "Tag": "tag21"
1477 }
1478 ],
1479 "SliceP": [
1480 {
1481 "Tag": "tag22"
1482 },
1483 null,
1484 {
1485 "Tag": "tag23"
1486 }
1487 ],
1488 "PSlice": null,
1489 "PSliceP": null,
1490 "EmptySlice": [],
1491 "NilSlice": null,
1492 "StringSlice": [
1493 "str24",
1494 "str25",
1495 "str26"
1496 ],
1497 "ByteSlice": "Gxwd",
1498 "Small": {
1499 "Tag": "tag30"
1500 },
1501 "PSmall": {
1502 "Tag": "tag31"
1503 },
1504 "PPSmall": null,
1505 "Interface": 5.2,
1506 "PInterface": null
1507 }`
1508
1509 var allValueCompact = strings.Map(noSpace, allValueIndent)
1510
1511 var pallValueIndent = `{
1512 "Bool": false,
1513 "Int": 0,
1514 "Int8": 0,
1515 "Int16": 0,
1516 "Int32": 0,
1517 "Int64": 0,
1518 "Uint": 0,
1519 "Uint8": 0,
1520 "Uint16": 0,
1521 "Uint32": 0,
1522 "Uint64": 0,
1523 "Uintptr": 0,
1524 "Float32": 0,
1525 "Float64": 0,
1526 "bar": "",
1527 "bar2": "",
1528 "IntStr": "0",
1529 "UintptrStr": "0",
1530 "PBool": true,
1531 "PInt": 2,
1532 "PInt8": 3,
1533 "PInt16": 4,
1534 "PInt32": 5,
1535 "PInt64": 6,
1536 "PUint": 7,
1537 "PUint8": 8,
1538 "PUint16": 9,
1539 "PUint32": 10,
1540 "PUint64": 11,
1541 "PUintptr": 12,
1542 "PFloat32": 14.1,
1543 "PFloat64": 15.1,
1544 "String": "",
1545 "PString": "16",
1546 "Map": null,
1547 "MapP": null,
1548 "PMap": {
1549 "17": {
1550 "Tag": "tag17"
1551 },
1552 "18": {
1553 "Tag": "tag18"
1554 }
1555 },
1556 "PMapP": {
1557 "19": {
1558 "Tag": "tag19"
1559 },
1560 "20": null
1561 },
1562 "EmptyMap": null,
1563 "NilMap": null,
1564 "Slice": null,
1565 "SliceP": null,
1566 "PSlice": [
1567 {
1568 "Tag": "tag20"
1569 },
1570 {
1571 "Tag": "tag21"
1572 }
1573 ],
1574 "PSliceP": [
1575 {
1576 "Tag": "tag22"
1577 },
1578 null,
1579 {
1580 "Tag": "tag23"
1581 }
1582 ],
1583 "EmptySlice": null,
1584 "NilSlice": null,
1585 "StringSlice": null,
1586 "ByteSlice": null,
1587 "Small": {
1588 "Tag": ""
1589 },
1590 "PSmall": null,
1591 "PPSmall": {
1592 "Tag": "tag31"
1593 },
1594 "Interface": null,
1595 "PInterface": 5.2
1596 }`
1597
1598 var pallValueCompact = strings.Map(noSpace, pallValueIndent)
1599
1600 func TestRefUnmarshal(t *testing.T) {
1601 type S struct {
1602 // Ref is defined in encode_test.go.
1603 R0 Ref
1604 R1 *Ref
1605 R2 RefText
1606 R3 *RefText
1607 }
1608 want := S{
1609 R0: 12,
1610 R1: new(Ref),
1611 R2: 13,
1612 R3: new(RefText),
1613 }
1614 *want.R1 = 12
1615 *want.R3 = 13
1616
1617 var got S
1618 if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil {
1619 t.Fatalf("Unmarshal: %v", err)
1620 }
1621 if !reflect.DeepEqual(got, want) {
1622 t.Errorf("got %+v, want %+v", got, want)
1623 }
1624 }
1625
1626 // Test that the empty string doesn't panic decoding when ,string is specified
1627 // Issue 3450
1628 func TestEmptyString(t *testing.T) {
1629 type T2 struct {
1630 Number1 int `json:",string"`
1631 Number2 int `json:",string"`
1632 }
1633 data := `{"Number1":"1", "Number2":""}`
1634 dec := NewDecoder(strings.NewReader(data))
1635 var t2 T2
1636 err := dec.Decode(&t2)
1637 if err == nil {
1638 t.Fatal("Decode: did not return error")
1639 }
1640 if t2.Number1 != 1 {
1641 t.Fatal("Decode: did not set Number1")
1642 }
1643 }
1644
1645 // Test that a null for ,string is not replaced with the previous quoted string (issue 7046).
1646 // It should also not be an error (issue 2540, issue 8587).
1647 func TestNullString(t *testing.T) {
1648 type T struct {
1649 A int `json:",string"`
1650 B int `json:",string"`
1651 C *int `json:",string"`
1652 }
1653 data := []byte(`{"A": "1", "B": null, "C": null}`)
1654 var s T
1655 s.B = 1
1656 s.C = new(int)
1657 *s.C = 2
1658 err := Unmarshal(data, &s)
1659 if err != nil {
1660 t.Fatalf("Unmarshal: %v", err)
1661 }
1662 if s.B != 1 || s.C != nil {
1663 t.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s.B, s.C)
1664 }
1665 }
1666
1667 func intp(x int) *int {
1668 p := new(int)
1669 *p = x
1670 return p
1671 }
1672
1673 func intpp(x *int) **int {
1674 pp := new(*int)
1675 *pp = x
1676 return pp
1677 }
1678
1679 var interfaceSetTests = []struct {
1680 pre any
1681 json string
1682 post any
1683 }{
1684 {"foo", `"bar"`, "bar"},
1685 {"foo", `2`, 2.0},
1686 {"foo", `true`, true},
1687 {"foo", `null`, nil},
1688
1689 {nil, `null`, nil},
1690 {new(int), `null`, nil},
1691 {(*int)(nil), `null`, nil},
1692 {new(*int), `null`, new(*int)},
1693 {(**int)(nil), `null`, nil},
1694 {intp(1), `null`, nil},
1695 {intpp(nil), `null`, intpp(nil)},
1696 {intpp(intp(1)), `null`, intpp(nil)},
1697 }
1698
1699 func TestInterfaceSet(t *testing.T) {
1700 for _, tt := range interfaceSetTests {
1701 b := struct{ X any }{tt.pre}
1702 blob := `{"X":` + tt.json + `}`
1703 if err := Unmarshal([]byte(blob), &b); err != nil {
1704 t.Errorf("Unmarshal %#q: %v", blob, err)
1705 continue
1706 }
1707 if !reflect.DeepEqual(b.X, tt.post) {
1708 t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post)
1709 }
1710 }
1711 }
1712
1713 type NullTest struct {
1714 Bool bool
1715 Int int
1716 Int8 int8
1717 Int16 int16
1718 Int32 int32
1719 Int64 int64
1720 Uint uint
1721 Uint8 uint8
1722 Uint16 uint16
1723 Uint32 uint32
1724 Uint64 uint64
1725 Float32 float32
1726 Float64 float64
1727 String string
1728 PBool *bool
1729 Map map[string]string
1730 Slice []string
1731 Interface any
1732
1733 PRaw *RawMessage
1734 PTime *time.Time
1735 PBigInt *big.Int
1736 PText *MustNotUnmarshalText
1737 PBuffer *bytes.Buffer // has methods, just not relevant ones
1738 PStruct *struct{}
1739
1740 Raw RawMessage
1741 Time time.Time
1742 BigInt big.Int
1743 Text MustNotUnmarshalText
1744 Buffer bytes.Buffer
1745 Struct struct{}
1746 }
1747
1748 type NullTestStrings struct {
1749 Bool bool `json:",string"`
1750 Int int `json:",string"`
1751 Int8 int8 `json:",string"`
1752 Int16 int16 `json:",string"`
1753 Int32 int32 `json:",string"`
1754 Int64 int64 `json:",string"`
1755 Uint uint `json:",string"`
1756 Uint8 uint8 `json:",string"`
1757 Uint16 uint16 `json:",string"`
1758 Uint32 uint32 `json:",string"`
1759 Uint64 uint64 `json:",string"`
1760 Float32 float32 `json:",string"`
1761 Float64 float64 `json:",string"`
1762 String string `json:",string"`
1763 PBool *bool `json:",string"`
1764 Map map[string]string `json:",string"`
1765 Slice []string `json:",string"`
1766 Interface any `json:",string"`
1767
1768 PRaw *RawMessage `json:",string"`
1769 PTime *time.Time `json:",string"`
1770 PBigInt *big.Int `json:",string"`
1771 PText *MustNotUnmarshalText `json:",string"`
1772 PBuffer *bytes.Buffer `json:",string"`
1773 PStruct *struct{} `json:",string"`
1774
1775 Raw RawMessage `json:",string"`
1776 Time time.Time `json:",string"`
1777 BigInt big.Int `json:",string"`
1778 Text MustNotUnmarshalText `json:",string"`
1779 Buffer bytes.Buffer `json:",string"`
1780 Struct struct{} `json:",string"`
1781 }
1782
1783 // JSON null values should be ignored for primitives and string values instead of resulting in an error.
1784 // Issue 2540
1785 func TestUnmarshalNulls(t *testing.T) {
1786 // Unmarshal docs:
1787 // The JSON null value unmarshals into an interface, map, pointer, or slice
1788 // by setting that Go value to nil. Because null is often used in JSON to mean
1789 // ``not present,'' unmarshaling a JSON null into any other Go type has no effect
1790 // on the value and produces no error.
1791
1792 jsonData := []byte(`{
1793 "Bool" : null,
1794 "Int" : null,
1795 "Int8" : null,
1796 "Int16" : null,
1797 "Int32" : null,
1798 "Int64" : null,
1799 "Uint" : null,
1800 "Uint8" : null,
1801 "Uint16" : null,
1802 "Uint32" : null,
1803 "Uint64" : null,
1804 "Float32" : null,
1805 "Float64" : null,
1806 "String" : null,
1807 "PBool": null,
1808 "Map": null,
1809 "Slice": null,
1810 "Interface": null,
1811 "PRaw": null,
1812 "PTime": null,
1813 "PBigInt": null,
1814 "PText": null,
1815 "PBuffer": null,
1816 "PStruct": null,
1817 "Raw": null,
1818 "Time": null,
1819 "BigInt": null,
1820 "Text": null,
1821 "Buffer": null,
1822 "Struct": null
1823 }`)
1824 nulls := NullTest{
1825 Bool: true,
1826 Int: 2,
1827 Int8: 3,
1828 Int16: 4,
1829 Int32: 5,
1830 Int64: 6,
1831 Uint: 7,
1832 Uint8: 8,
1833 Uint16: 9,
1834 Uint32: 10,
1835 Uint64: 11,
1836 Float32: 12.1,
1837 Float64: 13.1,
1838 String: "14",
1839 PBool: new(bool),
1840 Map: map[string]string{},
1841 Slice: []string{},
1842 Interface: new(MustNotUnmarshalJSON),
1843 PRaw: new(RawMessage),
1844 PTime: new(time.Time),
1845 PBigInt: new(big.Int),
1846 PText: new(MustNotUnmarshalText),
1847 PStruct: new(struct{}),
1848 PBuffer: new(bytes.Buffer),
1849 Raw: RawMessage("123"),
1850 Time: time.Unix(123456789, 0),
1851 BigInt: *big.NewInt(123),
1852 }
1853
1854 before := nulls.Time.String()
1855
1856 err := Unmarshal(jsonData, &nulls)
1857 if err != nil {
1858 t.Errorf("Unmarshal of null values failed: %v", err)
1859 }
1860 if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
1861 nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
1862 nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {
1863 t.Errorf("Unmarshal of null values affected primitives")
1864 }
1865
1866 if nulls.PBool != nil {
1867 t.Errorf("Unmarshal of null did not clear nulls.PBool")
1868 }
1869 if nulls.Map != nil {
1870 t.Errorf("Unmarshal of null did not clear nulls.Map")
1871 }
1872 if nulls.Slice != nil {
1873 t.Errorf("Unmarshal of null did not clear nulls.Slice")
1874 }
1875 if nulls.Interface != nil {
1876 t.Errorf("Unmarshal of null did not clear nulls.Interface")
1877 }
1878 if nulls.PRaw != nil {
1879 t.Errorf("Unmarshal of null did not clear nulls.PRaw")
1880 }
1881 if nulls.PTime != nil {
1882 t.Errorf("Unmarshal of null did not clear nulls.PTime")
1883 }
1884 if nulls.PBigInt != nil {
1885 t.Errorf("Unmarshal of null did not clear nulls.PBigInt")
1886 }
1887 if nulls.PText != nil {
1888 t.Errorf("Unmarshal of null did not clear nulls.PText")
1889 }
1890 if nulls.PBuffer != nil {
1891 t.Errorf("Unmarshal of null did not clear nulls.PBuffer")
1892 }
1893 if nulls.PStruct != nil {
1894 t.Errorf("Unmarshal of null did not clear nulls.PStruct")
1895 }
1896
1897 if string(nulls.Raw) != "null" {
1898 t.Errorf("Unmarshal of RawMessage null did not record null: %v", string(nulls.Raw))
1899 }
1900 if nulls.Time.String() != before {
1901 t.Errorf("Unmarshal of time.Time null set time to %v", nulls.Time.String())
1902 }
1903 if nulls.BigInt.String() != "123" {
1904 t.Errorf("Unmarshal of big.Int null set int to %v", nulls.BigInt.String())
1905 }
1906 }
1907
1908 type MustNotUnmarshalJSON struct{}
1909
1910 func (x MustNotUnmarshalJSON) UnmarshalJSON(data []byte) error {
1911 return errors.New("MustNotUnmarshalJSON was used")
1912 }
1913
1914 type MustNotUnmarshalText struct{}
1915
1916 func (x MustNotUnmarshalText) UnmarshalText(text []byte) error {
1917 return errors.New("MustNotUnmarshalText was used")
1918 }
1919
1920 func TestStringKind(t *testing.T) {
1921 type stringKind string
1922
1923 var m1, m2 map[stringKind]int
1924 m1 = map[stringKind]int{
1925 "foo": 42,
1926 }
1927
1928 data, err := Marshal(m1)
1929 if err != nil {
1930 t.Errorf("Unexpected error marshaling: %v", err)
1931 }
1932
1933 err = Unmarshal(data, &m2)
1934 if err != nil {
1935 t.Errorf("Unexpected error unmarshaling: %v", err)
1936 }
1937
1938 if !reflect.DeepEqual(m1, m2) {
1939 t.Error("Items should be equal after encoding and then decoding")
1940 }
1941 }
1942
1943 // Custom types with []byte as underlying type could not be marshaled
1944 // and then unmarshaled.
1945 // Issue 8962.
1946 func TestByteKind(t *testing.T) {
1947 type byteKind []byte
1948
1949 a := byteKind("hello")
1950
1951 data, err := Marshal(a)
1952 if err != nil {
1953 t.Error(err)
1954 }
1955 var b byteKind
1956 err = Unmarshal(data, &b)
1957 if err != nil {
1958 t.Fatal(err)
1959 }
1960 if !reflect.DeepEqual(a, b) {
1961 t.Errorf("expected %v == %v", a, b)
1962 }
1963 }
1964
1965 // The fix for issue 8962 introduced a regression.
1966 // Issue 12921.
1967 func TestSliceOfCustomByte(t *testing.T) {
1968 type Uint8 uint8
1969
1970 a := []Uint8("hello")
1971
1972 data, err := Marshal(a)
1973 if err != nil {
1974 t.Fatal(err)
1975 }
1976 var b []Uint8
1977 err = Unmarshal(data, &b)
1978 if err != nil {
1979 t.Fatal(err)
1980 }
1981 if !reflect.DeepEqual(a, b) {
1982 t.Fatalf("expected %v == %v", a, b)
1983 }
1984 }
1985
1986 var decodeTypeErrorTests = []struct {
1987 dest any
1988 src string
1989 }{
1990 {new(string), `{"user": "name"}`}, // issue 4628.
1991 {new(error), `{}`}, // issue 4222
1992 {new(error), `[]`},
1993 {new(error), `""`},
1994 {new(error), `123`},
1995 {new(error), `true`},
1996 }
1997
1998 func TestUnmarshalTypeError(t *testing.T) {
1999 for _, item := range decodeTypeErrorTests {
2000 err := Unmarshal([]byte(item.src), item.dest)
2001 if _, ok := err.(*UnmarshalTypeError); !ok {
2002 t.Errorf("expected type error for Unmarshal(%q, type %T): got %T",
2003 item.src, item.dest, err)
2004 }
2005 }
2006 }
2007
2008 var unmarshalSyntaxTests = []string{
2009 "tru",
2010 "fals",
2011 "nul",
2012 "123e",
2013 `"hello`,
2014 `[1,2,3`,
2015 `{"key":1`,
2016 `{"key":1,`,
2017 }
2018
2019 func TestUnmarshalSyntax(t *testing.T) {
2020 var x any
2021 for _, src := range unmarshalSyntaxTests {
2022 err := Unmarshal([]byte(src), &x)
2023 if _, ok := err.(*SyntaxError); !ok {
2024 t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err)
2025 }
2026 }
2027 }
2028
2029 // Test handling of unexported fields that should be ignored.
2030 // Issue 4660
2031 type unexportedFields struct {
2032 Name string
2033 m map[string]any `json:"-"`
2034 m2 map[string]any `json:"abcd"`
2035
2036 s []int `json:"-"`
2037 }
2038
2039 func TestUnmarshalUnexported(t *testing.T) {
2040 input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}, "s": [2, 3]}`
2041 want := &unexportedFields{Name: "Bob"}
2042
2043 out := &unexportedFields{}
2044 err := Unmarshal([]byte(input), out)
2045 if err != nil {
2046 t.Errorf("got error %v, expected nil", err)
2047 }
2048 if !reflect.DeepEqual(out, want) {
2049 t.Errorf("got %q, want %q", out, want)
2050 }
2051 }
2052
2053 // Time3339 is a time.Time which encodes to and from JSON
2054 // as an RFC 3339 time in UTC.
2055 type Time3339 time.Time
2056
2057 func (t *Time3339) UnmarshalJSON(b []byte) error {
2058 if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
2059 return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b)
2060 }
2061 tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1]))
2062 if err != nil {
2063 return err
2064 }
2065 *t = Time3339(tm)
2066 return nil
2067 }
2068
2069 func TestUnmarshalJSONLiteralError(t *testing.T) {
2070 var t3 Time3339
2071 err := Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3)
2072 if err == nil {
2073 t.Fatalf("expected error; got time %v", time.Time(t3))
2074 }
2075 if !strings.Contains(err.Error(), "range") {
2076 t.Errorf("got err = %v; want out of range error", err)
2077 }
2078 }
2079
2080 // Test that extra object elements in an array do not result in a
2081 // "data changing underfoot" error.
2082 // Issue 3717
2083 func TestSkipArrayObjects(t *testing.T) {
2084 json := `[{}]`
2085 var dest [0]any
2086
2087 err := Unmarshal([]byte(json), &dest)
2088 if err != nil {
2089 t.Errorf("got error %q, want nil", err)
2090 }
2091 }
2092
2093 // Test semantics of pre-filled struct fields and pre-filled map fields.
2094 // Issue 4900.
2095 func TestPrefilled(t *testing.T) {
2096 ptrToMap := func(m map[string]any) *map[string]any { return &m }
2097
2098 // Values here change, cannot reuse table across runs.
2099 prefillTests := []struct {
2100 in string
2101 ptr any
2102 out any
2103 }{
2104 {
2105 in: `{"X": 1, "Y": 2}`,
2106 ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5},
2107 out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5},
2108 },
2109 {
2110 in: `{"X": 1, "Y": 2}`,
2111 ptr: ptrToMap(map[string]any{"X": float32(3), "Y": int16(4), "Z": 1.5}),
2112 out: ptrToMap(map[string]any{"X": float64(1), "Y": float64(2), "Z": 1.5}),
2113 },
2114 }
2115
2116 for _, tt := range prefillTests {
2117 ptrstr := fmt.Sprintf("%v", tt.ptr)
2118 err := Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here
2119 if err != nil {
2120 t.Errorf("Unmarshal: %v", err)
2121 }
2122 if !reflect.DeepEqual(tt.ptr, tt.out) {
2123 t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out)
2124 }
2125 }
2126 }
2127
2128 var invalidUnmarshalTests = []struct {
2129 v any
2130 want string
2131 }{
2132 {nil, "json: Unmarshal(nil)"},
2133 {struct{}{}, "json: Unmarshal(non-pointer struct {})"},
2134 {(*int)(nil), "json: Unmarshal(nil *int)"},
2135 }
2136
2137 func TestInvalidUnmarshal(t *testing.T) {
2138 buf := []byte(`{"a":"1"}`)
2139 for _, tt := range invalidUnmarshalTests {
2140 err := Unmarshal(buf, tt.v)
2141 if err == nil {
2142 t.Errorf("Unmarshal expecting error, got nil")
2143 continue
2144 }
2145 if got := err.Error(); got != tt.want {
2146 t.Errorf("Unmarshal = %q; want %q", got, tt.want)
2147 }
2148 }
2149 }
2150
2151 var invalidUnmarshalTextTests = []struct {
2152 v any
2153 want string
2154 }{
2155 {nil, "json: Unmarshal(nil)"},
2156 {struct{}{}, "json: Unmarshal(non-pointer struct {})"},
2157 {(*int)(nil), "json: Unmarshal(nil *int)"},
2158 {new(net.IP), "json: cannot unmarshal number into Go value of type *net.IP"},
2159 }
2160
2161 func TestInvalidUnmarshalText(t *testing.T) {
2162 buf := []byte(`123`)
2163 for _, tt := range invalidUnmarshalTextTests {
2164 err := Unmarshal(buf, tt.v)
2165 if err == nil {
2166 t.Errorf("Unmarshal expecting error, got nil")
2167 continue
2168 }
2169 if got := err.Error(); got != tt.want {
2170 t.Errorf("Unmarshal = %q; want %q", got, tt.want)
2171 }
2172 }
2173 }
2174
2175 // Test that string option is ignored for invalid types.
2176 // Issue 9812.
2177 func TestInvalidStringOption(t *testing.T) {
2178 num := 0
2179 item := struct {
2180 T time.Time `json:",string"`
2181 M map[string]string `json:",string"`
2182 S []string `json:",string"`
2183 A [1]string `json:",string"`
2184 I any `json:",string"`
2185 P *int `json:",string"`
2186 }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num}
2187
2188 data, err := Marshal(item)
2189 if err != nil {
2190 t.Fatalf("Marshal: %v", err)
2191 }
2192
2193 err = Unmarshal(data, &item)
2194 if err != nil {
2195 t.Fatalf("Unmarshal: %v", err)
2196 }
2197 }
2198
2199 // Test unmarshal behavior with regards to embedded unexported structs.
2200 //
2201 // (Issue 21357) If the embedded struct is a pointer and is unallocated,
2202 // this returns an error because unmarshal cannot set the field.
2203 //
2204 // (Issue 24152) If the embedded struct is given an explicit name,
2205 // ensure that the normal unmarshal logic does not panic in reflect.
2206 //
2207 // (Issue 28145) If the embedded struct is given an explicit name and has
2208 // exported methods, don't cause a panic trying to get its value.
2209 func TestUnmarshalEmbeddedUnexported(t *testing.T) {
2210 type (
2211 embed1 struct{ Q int }
2212 embed2 struct{ Q int }
2213 embed3 struct {
2214 Q int64 `json:",string"`
2215 }
2216 S1 struct {
2217 *embed1
2218 R int
2219 }
2220 S2 struct {
2221 *embed1
2222 Q int
2223 }
2224 S3 struct {
2225 embed1
2226 R int
2227 }
2228 S4 struct {
2229 *embed1
2230 embed2
2231 }
2232 S5 struct {
2233 *embed3
2234 R int
2235 }
2236 S6 struct {
2237 embed1 `json:"embed1"`
2238 }
2239 S7 struct {
2240 embed1 `json:"embed1"`
2241 embed2
2242 }
2243 S8 struct {
2244 embed1 `json:"embed1"`
2245 embed2 `json:"embed2"`
2246 Q int
2247 }
2248 S9 struct {
2249 unexportedWithMethods `json:"embed"`
2250 }
2251 )
2252
2253 tests := []struct {
2254 in string
2255 ptr any
2256 out any
2257 err error
2258 }{{
2259 // Error since we cannot set S1.embed1, but still able to set S1.R.
2260 in: `{"R":2,"Q":1}`,
2261 ptr: new(S1),
2262 out: &S1{R: 2},
2263 err: fmt.Errorf("json: cannot set embedded pointer to unexported struct: json.embed1"),
2264 }, {
2265 // The top level Q field takes precedence.
2266 in: `{"Q":1}`,
2267 ptr: new(S2),
2268 out: &S2{Q: 1},
2269 }, {
2270 // No issue with non-pointer variant.
2271 in: `{"R":2,"Q":1}`,
2272 ptr: new(S3),
2273 out: &S3{embed1: embed1{Q: 1}, R: 2},
2274 }, {
2275 // No error since both embedded structs have field R, which annihilate each other.
2276 // Thus, no attempt is made at setting S4.embed1.
2277 in: `{"R":2}`,
2278 ptr: new(S4),
2279 out: new(S4),
2280 }, {
2281 // Error since we cannot set S5.embed1, but still able to set S5.R.
2282 in: `{"R":2,"Q":1}`,
2283 ptr: new(S5),
2284 out: &S5{R: 2},
2285 err: fmt.Errorf("json: cannot set embedded pointer to unexported struct: json.embed3"),
2286 }, {
2287 // Issue 24152, ensure decodeState.indirect does not panic.
2288 in: `{"embed1": {"Q": 1}}`,
2289 ptr: new(S6),
2290 out: &S6{embed1{1}},
2291 }, {
2292 // Issue 24153, check that we can still set forwarded fields even in
2293 // the presence of a name conflict.
2294 //
2295 // This relies on obscure behavior of reflect where it is possible
2296 // to set a forwarded exported field on an unexported embedded struct
2297 // even though there is a name conflict, even when it would have been
2298 // impossible to do so according to Go visibility rules.
2299 // Go forbids this because it is ambiguous whether S7.Q refers to
2300 // S7.embed1.Q or S7.embed2.Q. Since embed1 and embed2 are unexported,
2301 // it should be impossible for an external package to set either Q.
2302 //
2303 // It is probably okay for a future reflect change to break this.
2304 in: `{"embed1": {"Q": 1}, "Q": 2}`,
2305 ptr: new(S7),
2306 out: &S7{embed1{1}, embed2{2}},
2307 }, {
2308 // Issue 24153, similar to the S7 case.
2309 in: `{"embed1": {"Q": 1}, "embed2": {"Q": 2}, "Q": 3}`,
2310 ptr: new(S8),
2311 out: &S8{embed1{1}, embed2{2}, 3},
2312 }, {
2313 // Issue 228145, similar to the cases above.
2314 in: `{"embed": {}}`,
2315 ptr: new(S9),
2316 out: &S9{},
2317 }}
2318
2319 for i, tt := range tests {
2320 err := Unmarshal([]byte(tt.in), tt.ptr)
2321 if !equalError(err, tt.err) {
2322 t.Errorf("#%d: %v, want %v", i, err, tt.err)
2323 }
2324 if !reflect.DeepEqual(tt.ptr, tt.out) {
2325 t.Errorf("#%d: mismatch\ngot: %#+v\nwant: %#+v", i, tt.ptr, tt.out)
2326 }
2327 }
2328 }
2329
2330 type unmarshalPanic struct{}
2331
2332 func (unmarshalPanic) UnmarshalJSON([]byte) error { panic(0xdead) }
2333
2334 func TestUnmarshalPanic(t *testing.T) {
2335 defer func() {
2336 if got := recover(); !reflect.DeepEqual(got, 0xdead) {
2337 t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
2338 }
2339 }()
2340 Unmarshal([]byte("{}"), &unmarshalPanic{})
2341 t.Fatalf("Unmarshal should have panicked")
2342 }
2343
2344 // The decoder used to hang if decoding into an interface pointing to its own address.
2345 // See golang.org/issues/31740.
2346 func TestUnmarshalRecursivePointer(t *testing.T) {
2347 var v any
2348 v = &v
2349 data := []byte(`{"a": "b"}`)
2350
2351 if err := Unmarshal(data, v); err != nil {
2352 t.Fatal(err)
2353 }
2354 }