Debian Codegraph @

encode_test.go

raw
1 package json_test
2
3 import (
4 "bytes"
5 "context"
6 "encoding"
7 stdjson "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "log"
12 "math"
13 "math/big"
14 "reflect"
15 "regexp"
16 "strconv"
17 "strings"
18 "testing"
19 "time"
20
21 "github.com/goccy/go-json"
22 )
23
24 type recursiveT struct {
25 A *recursiveT `json:"a,omitempty"`
26 B *recursiveU `json:"b,omitempty"`
27 C *recursiveU `json:"c,omitempty"`
28 D string `json:"d,omitempty"`
29 }
30
31 type recursiveU struct {
32 T *recursiveT `json:"t,omitempty"`
33 }
34
35 func Test_Marshal(t *testing.T) {
36 t.Run("int", func(t *testing.T) {
37 bytes, err := json.Marshal(-10)
38 assertErr(t, err)
39 assertEq(t, "int", `-10`, string(bytes))
40 })
41 t.Run("int8", func(t *testing.T) {
42 bytes, err := json.Marshal(int8(-11))
43 assertErr(t, err)
44 assertEq(t, "int8", `-11`, string(bytes))
45 })
46 t.Run("int16", func(t *testing.T) {
47 bytes, err := json.Marshal(int16(-12))
48 assertErr(t, err)
49 assertEq(t, "int16", `-12`, string(bytes))
50 })
51 t.Run("int32", func(t *testing.T) {
52 bytes, err := json.Marshal(int32(-13))
53 assertErr(t, err)
54 assertEq(t, "int32", `-13`, string(bytes))
55 })
56 t.Run("int64", func(t *testing.T) {
57 bytes, err := json.Marshal(int64(-14))
58 assertErr(t, err)
59 assertEq(t, "int64", `-14`, string(bytes))
60 })
61 t.Run("uint", func(t *testing.T) {
62 bytes, err := json.Marshal(uint(10))
63 assertErr(t, err)
64 assertEq(t, "uint", `10`, string(bytes))
65 })
66 t.Run("uint8", func(t *testing.T) {
67 bytes, err := json.Marshal(uint8(11))
68 assertErr(t, err)
69 assertEq(t, "uint8", `11`, string(bytes))
70 })
71 t.Run("uint16", func(t *testing.T) {
72 bytes, err := json.Marshal(uint16(12))
73 assertErr(t, err)
74 assertEq(t, "uint16", `12`, string(bytes))
75 })
76 t.Run("uint32", func(t *testing.T) {
77 bytes, err := json.Marshal(uint32(13))
78 assertErr(t, err)
79 assertEq(t, "uint32", `13`, string(bytes))
80 })
81 t.Run("uint64", func(t *testing.T) {
82 bytes, err := json.Marshal(uint64(14))
83 assertErr(t, err)
84 assertEq(t, "uint64", `14`, string(bytes))
85 })
86 t.Run("float32", func(t *testing.T) {
87 bytes, err := json.Marshal(float32(3.14))
88 assertErr(t, err)
89 assertEq(t, "float32", `3.14`, string(bytes))
90 })
91 t.Run("float64", func(t *testing.T) {
92 bytes, err := json.Marshal(float64(3.14))
93 assertErr(t, err)
94 assertEq(t, "float64", `3.14`, string(bytes))
95 })
96 t.Run("bool", func(t *testing.T) {
97 bytes, err := json.Marshal(true)
98 assertErr(t, err)
99 assertEq(t, "bool", `true`, string(bytes))
100 })
101 t.Run("string", func(t *testing.T) {
102 bytes, err := json.Marshal("hello world")
103 assertErr(t, err)
104 assertEq(t, "string", `"hello world"`, string(bytes))
105 })
106 t.Run("struct", func(t *testing.T) {
107 bytes, err := json.Marshal(struct {
108 A int `json:"a"`
109 B uint `json:"b"`
110 C string `json:"c"`
111 D int `json:"-"` // ignore field
112 a int `json:"aa"` // private field
113 }{
114 A: -1,
115 B: 1,
116 C: "hello world",
117 })
118 assertErr(t, err)
119 assertEq(t, "struct", `{"a":-1,"b":1,"c":"hello world"}`, string(bytes))
120 t.Run("null", func(t *testing.T) {
121 type T struct {
122 A *struct{} `json:"a"`
123 }
124 var v T
125 bytes, err := json.Marshal(&v)
126 assertErr(t, err)
127 assertEq(t, "struct", `{"a":null}`, string(bytes))
128 })
129 t.Run("recursive", func(t *testing.T) {
130 bytes, err := json.Marshal(recursiveT{
131 A: &recursiveT{
132 B: &recursiveU{
133 T: &recursiveT{
134 D: "hello",
135 },
136 },
137 C: &recursiveU{
138 T: &recursiveT{
139 D: "world",
140 },
141 },
142 },
143 })
144 assertErr(t, err)
145 assertEq(t, "recursive", `{"a":{"b":{"t":{"d":"hello"}},"c":{"t":{"d":"world"}}}}`, string(bytes))
146 })
147 t.Run("embedded", func(t *testing.T) {
148 type T struct {
149 A string `json:"a"`
150 }
151 type U struct {
152 *T
153 B string `json:"b"`
154 }
155 type T2 struct {
156 A string `json:"a,omitempty"`
157 }
158 type U2 struct {
159 *T2
160 B string `json:"b,omitempty"`
161 }
162 t.Run("exists field", func(t *testing.T) {
163 bytes, err := json.Marshal(&U{
164 T: &T{
165 A: "aaa",
166 },
167 B: "bbb",
168 })
169 assertErr(t, err)
170 assertEq(t, "embedded", `{"a":"aaa","b":"bbb"}`, string(bytes))
171 t.Run("omitempty", func(t *testing.T) {
172 bytes, err := json.Marshal(&U2{
173 T2: &T2{
174 A: "aaa",
175 },
176 B: "bbb",
177 })
178 assertErr(t, err)
179 assertEq(t, "embedded", `{"a":"aaa","b":"bbb"}`, string(bytes))
180 })
181 })
182 t.Run("none field", func(t *testing.T) {
183 bytes, err := json.Marshal(&U{
184 B: "bbb",
185 })
186 assertErr(t, err)
187 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes))
188 t.Run("omitempty", func(t *testing.T) {
189 bytes, err := json.Marshal(&U2{
190 B: "bbb",
191 })
192 assertErr(t, err)
193 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes))
194 })
195 })
196 })
197
198 t.Run("embedded with tag", func(t *testing.T) {
199 type T struct {
200 A string `json:"a"`
201 }
202 type U struct {
203 *T `json:"t"`
204 B string `json:"b"`
205 }
206 type T2 struct {
207 A string `json:"a,omitempty"`
208 }
209 type U2 struct {
210 *T2 `json:"t,omitempty"`
211 B string `json:"b,omitempty"`
212 }
213 t.Run("exists field", func(t *testing.T) {
214 bytes, err := json.Marshal(&U{
215 T: &T{
216 A: "aaa",
217 },
218 B: "bbb",
219 })
220 assertErr(t, err)
221 assertEq(t, "embedded", `{"t":{"a":"aaa"},"b":"bbb"}`, string(bytes))
222 t.Run("omitempty", func(t *testing.T) {
223 bytes, err := json.Marshal(&U2{
224 T2: &T2{
225 A: "aaa",
226 },
227 B: "bbb",
228 })
229 assertErr(t, err)
230 assertEq(t, "embedded", `{"t":{"a":"aaa"},"b":"bbb"}`, string(bytes))
231 })
232 })
233
234 t.Run("none field", func(t *testing.T) {
235 bytes, err := json.Marshal(&U{
236 B: "bbb",
237 })
238 assertErr(t, err)
239 assertEq(t, "embedded", `{"t":null,"b":"bbb"}`, string(bytes))
240 t.Run("omitempty", func(t *testing.T) {
241 bytes, err := json.Marshal(&U2{
242 B: "bbb",
243 })
244 assertErr(t, err)
245 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes))
246 })
247 })
248 })
249
250 t.Run("omitempty", func(t *testing.T) {
251 type T struct {
252 A int `json:",omitempty"`
253 B int8 `json:",omitempty"`
254 C int16 `json:",omitempty"`
255 D int32 `json:",omitempty"`
256 E int64 `json:",omitempty"`
257 F uint `json:",omitempty"`
258 G uint8 `json:",omitempty"`
259 H uint16 `json:",omitempty"`
260 I uint32 `json:",omitempty"`
261 J uint64 `json:",omitempty"`
262 K float32 `json:",omitempty"`
263 L float64 `json:",omitempty"`
264 O string `json:",omitempty"`
265 P bool `json:",omitempty"`
266 Q []int `json:",omitempty"`
267 R map[string]any `json:",omitempty"`
268 S *struct{} `json:",omitempty"`
269 T int `json:"t,omitempty"`
270 }
271 var v T
272 v.T = 1
273 bytes, err := json.Marshal(&v)
274 assertErr(t, err)
275 assertEq(t, "struct", `{"t":1}`, string(bytes))
276 t.Run("int", func(t *testing.T) {
277 var v struct {
278 A int `json:"a,omitempty"`
279 B int `json:"b"`
280 }
281 v.B = 1
282 bytes, err := json.Marshal(&v)
283 assertErr(t, err)
284 assertEq(t, "int", `{"b":1}`, string(bytes))
285 })
286 t.Run("int8", func(t *testing.T) {
287 var v struct {
288 A int `json:"a,omitempty"`
289 B int8 `json:"b"`
290 }
291 v.B = 1
292 bytes, err := json.Marshal(&v)
293 assertErr(t, err)
294 assertEq(t, "int8", `{"b":1}`, string(bytes))
295 })
296 t.Run("int16", func(t *testing.T) {
297 var v struct {
298 A int `json:"a,omitempty"`
299 B int16 `json:"b"`
300 }
301 v.B = 1
302 bytes, err := json.Marshal(&v)
303 assertErr(t, err)
304 assertEq(t, "int16", `{"b":1}`, string(bytes))
305 })
306 t.Run("int32", func(t *testing.T) {
307 var v struct {
308 A int `json:"a,omitempty"`
309 B int32 `json:"b"`
310 }
311 v.B = 1
312 bytes, err := json.Marshal(&v)
313 assertErr(t, err)
314 assertEq(t, "int32", `{"b":1}`, string(bytes))
315 })
316 t.Run("int64", func(t *testing.T) {
317 var v struct {
318 A int `json:"a,omitempty"`
319 B int64 `json:"b"`
320 }
321 v.B = 1
322 bytes, err := json.Marshal(&v)
323 assertErr(t, err)
324 assertEq(t, "int64", `{"b":1}`, string(bytes))
325 })
326 t.Run("string", func(t *testing.T) {
327 var v struct {
328 A int `json:"a,omitempty"`
329 B string `json:"b"`
330 }
331 v.B = "b"
332 bytes, err := json.Marshal(&v)
333 assertErr(t, err)
334 assertEq(t, "string", `{"b":"b"}`, string(bytes))
335 })
336 t.Run("float32", func(t *testing.T) {
337 var v struct {
338 A int `json:"a,omitempty"`
339 B float32 `json:"b"`
340 }
341 v.B = 1.1
342 bytes, err := json.Marshal(&v)
343 assertErr(t, err)
344 assertEq(t, "float32", `{"b":1.1}`, string(bytes))
345 })
346 t.Run("float64", func(t *testing.T) {
347 var v struct {
348 A int `json:"a,omitempty"`
349 B float64 `json:"b"`
350 }
351 v.B = 3.14
352 bytes, err := json.Marshal(&v)
353 assertErr(t, err)
354 assertEq(t, "float64", `{"b":3.14}`, string(bytes))
355 })
356 t.Run("slice", func(t *testing.T) {
357 var v struct {
358 A int `json:"a,omitempty"`
359 B []int `json:"b"`
360 }
361 v.B = []int{1, 2, 3}
362 bytes, err := json.Marshal(&v)
363 assertErr(t, err)
364 assertEq(t, "slice", `{"b":[1,2,3]}`, string(bytes))
365 })
366 t.Run("array", func(t *testing.T) {
367 var v struct {
368 A int `json:"a,omitempty"`
369 B [2]int `json:"b"`
370 }
371 v.B = [2]int{1, 2}
372 bytes, err := json.Marshal(&v)
373 assertErr(t, err)
374 assertEq(t, "array", `{"b":[1,2]}`, string(bytes))
375 })
376 t.Run("map", func(t *testing.T) {
377 v := new(struct {
378 A int `json:"a,omitempty"`
379 B map[string]any `json:"b"`
380 })
381 v.B = map[string]any{"c": 1}
382 bytes, err := json.Marshal(v)
383 assertErr(t, err)
384 assertEq(t, "array", `{"b":{"c":1}}`, string(bytes))
385 })
386 })
387 t.Run("head_omitempty", func(t *testing.T) {
388 type T struct {
389 A *struct{} `json:"a,omitempty"`
390 }
391 var v T
392 bytes, err := json.Marshal(&v)
393 assertErr(t, err)
394 assertEq(t, "struct", `{}`, string(bytes))
395 })
396 t.Run("pointer_head_omitempty", func(t *testing.T) {
397 type V struct{}
398 type U struct {
399 B *V `json:"b,omitempty"`
400 }
401 type T struct {
402 A *U `json:"a"`
403 }
404 bytes, err := json.Marshal(&T{A: &U{}})
405 assertErr(t, err)
406 assertEq(t, "struct", `{"a":{}}`, string(bytes))
407 })
408 t.Run("head_int_omitempty", func(t *testing.T) {
409 type T struct {
410 A int `json:"a,omitempty"`
411 }
412 var v T
413 bytes, err := json.Marshal(&v)
414 assertErr(t, err)
415 assertEq(t, "struct", `{}`, string(bytes))
416 })
417 })
418 t.Run("slice", func(t *testing.T) {
419 t.Run("[]int", func(t *testing.T) {
420 bytes, err := json.Marshal([]int{1, 2, 3, 4})
421 assertErr(t, err)
422 assertEq(t, "[]int", `[1,2,3,4]`, string(bytes))
423 })
424 t.Run("[]any", func(t *testing.T) {
425 bytes, err := json.Marshal([]any{1, 2.1, "hello"})
426 assertErr(t, err)
427 assertEq(t, "[]any", `[1,2.1,"hello"]`, string(bytes))
428 })
429 t.Run("[]*time.Time", func(t *testing.T) {
430 bytes, err := json.Marshal([]*time.Time{nil})
431 assertErr(t, err)
432 assertEq(t, "[]*time.Time", `[null]`, string(bytes))
433 })
434 })
435
436 t.Run("array", func(t *testing.T) {
437 bytes, err := json.Marshal([4]int{1, 2, 3, 4})
438 assertErr(t, err)
439 assertEq(t, "array", `[1,2,3,4]`, string(bytes))
440 })
441 t.Run("map", func(t *testing.T) {
442 t.Run("map[string]int", func(t *testing.T) {
443 v := map[string]int{
444 "a": 1,
445 "b": 2,
446 "c": 3,
447 "d": 4,
448 }
449 bytes, err := json.Marshal(v)
450 assertErr(t, err)
451 assertEq(t, "map", `{"a":1,"b":2,"c":3,"d":4}`, string(bytes))
452 b, err := json.MarshalWithOption(v, json.UnorderedMap())
453 assertErr(t, err)
454 assertEq(t, "unordered map", len(`{"a":1,"b":2,"c":3,"d":4}`), len(string(b)))
455 })
456 t.Run("map[string]any", func(t *testing.T) {
457 type T struct {
458 A int
459 }
460 v := map[string]any{
461 "a": 1,
462 "b": 2.1,
463 "c": &T{
464 A: 10,
465 },
466 "d": 4,
467 }
468 bytes, err := json.Marshal(v)
469 assertErr(t, err)
470 assertEq(t, "map[string]any", `{"a":1,"b":2.1,"c":{"A":10},"d":4}`, string(bytes))
471 })
472 })
473 }
474
475 type mustErrTypeForDebug struct{}
476
477 func (mustErrTypeForDebug) MarshalJSON() ([]byte, error) {
478 panic("panic")
479 return nil, fmt.Errorf("panic")
480 }
481
482 func TestDebugMode(t *testing.T) {
483 defer func() {
484 if err := recover(); err == nil {
485 t.Fatal("expected error")
486 }
487 }()
488 var buf bytes.Buffer
489 json.MarshalWithOption(mustErrTypeForDebug{}, json.Debug(), json.DebugWith(&buf))
490 }
491
492 func TestIssue116(t *testing.T) {
493 t.Run("first", func(t *testing.T) {
494 type Boo struct{ B string }
495 type Struct struct {
496 A int
497 Boo *Boo
498 }
499 type Embedded struct {
500 Struct
501 }
502 b, err := json.Marshal(Embedded{Struct: Struct{
503 A: 1,
504 Boo: &Boo{B: "foo"},
505 }})
506 if err != nil {
507 t.Fatal(err)
508 }
509 expected := `{"A":1,"Boo":{"B":"foo"}}`
510 actual := string(b)
511 if actual != expected {
512 t.Fatalf("expected %s but got %s", expected, actual)
513 }
514 })
515 t.Run("second", func(t *testing.T) {
516 type Boo struct{ B string }
517 type Struct struct {
518 A int
519 B *Boo
520 }
521 type Embedded struct {
522 Struct
523 }
524 b, err := json.Marshal(Embedded{Struct: Struct{
525 A: 1,
526 B: &Boo{B: "foo"},
527 }})
528 if err != nil {
529 t.Fatal(err)
530 }
531 actual := string(b)
532 expected := `{"A":1,"B":{"B":"foo"}}`
533 if actual != expected {
534 t.Fatalf("expected %s but got %s", expected, actual)
535 }
536 })
537 }
538
539 type marshalJSON struct{}
540
541 func (*marshalJSON) MarshalJSON() ([]byte, error) {
542 return []byte(`1`), nil
543 }
544
545 func Test_MarshalJSON(t *testing.T) {
546 t.Run("*struct", func(t *testing.T) {
547 bytes, err := json.Marshal(&marshalJSON{})
548 assertErr(t, err)
549 assertEq(t, "MarshalJSON", "1", string(bytes))
550 })
551 t.Run("time", func(t *testing.T) {
552 bytes, err := json.Marshal(time.Time{})
553 assertErr(t, err)
554 assertEq(t, "MarshalJSON", `"0001-01-01T00:00:00Z"`, string(bytes))
555 })
556 }
557
558 func Test_MarshalIndent(t *testing.T) {
559 prefix := "-"
560 indent := "\t"
561 t.Run("struct", func(t *testing.T) {
562 v := struct {
563 A int `json:"a"`
564 B uint `json:"b"`
565 C string `json:"c"`
566 D any `json:"d"`
567 X int `json:"-"` // ignore field
568 a int `json:"aa"` // private field
569 }{
570 A: -1,
571 B: 1,
572 C: "hello world",
573 D: struct {
574 E bool `json:"e"`
575 }{
576 E: true,
577 },
578 }
579 expected, err := stdjson.MarshalIndent(v, prefix, indent)
580 assertErr(t, err)
581 got, err := json.MarshalIndent(v, prefix, indent)
582 assertErr(t, err)
583 assertEq(t, "struct", string(expected), string(got))
584 })
585 t.Run("slice", func(t *testing.T) {
586 t.Run("[]int", func(t *testing.T) {
587 bytes, err := json.MarshalIndent([]int{1, 2, 3, 4}, prefix, indent)
588 assertErr(t, err)
589 result := "[\n-\t1,\n-\t2,\n-\t3,\n-\t4\n-]"
590 assertEq(t, "[]int", result, string(bytes))
591 })
592 t.Run("[]any", func(t *testing.T) {
593 bytes, err := json.MarshalIndent([]any{1, 2.1, "hello"}, prefix, indent)
594 assertErr(t, err)
595 result := "[\n-\t1,\n-\t2.1,\n-\t\"hello\"\n-]"
596 assertEq(t, "[]any", result, string(bytes))
597 })
598 })
599
600 t.Run("array", func(t *testing.T) {
601 bytes, err := json.MarshalIndent([4]int{1, 2, 3, 4}, prefix, indent)
602 assertErr(t, err)
603 result := "[\n-\t1,\n-\t2,\n-\t3,\n-\t4\n-]"
604 assertEq(t, "array", result, string(bytes))
605 })
606 t.Run("map", func(t *testing.T) {
607 t.Run("map[string]int", func(t *testing.T) {
608 bytes, err := json.MarshalIndent(map[string]int{
609 "a": 1,
610 "b": 2,
611 "c": 3,
612 "d": 4,
613 }, prefix, indent)
614 assertErr(t, err)
615 result := "{\n-\t\"a\": 1,\n-\t\"b\": 2,\n-\t\"c\": 3,\n-\t\"d\": 4\n-}"
616 assertEq(t, "map", result, string(bytes))
617 })
618 t.Run("map[string]any", func(t *testing.T) {
619 type T struct {
620 E int
621 F int
622 }
623 v := map[string]any{
624 "a": 1,
625 "b": 2.1,
626 "c": &T{
627 E: 10,
628 F: 11,
629 },
630 "d": 4,
631 }
632 bytes, err := json.MarshalIndent(v, prefix, indent)
633 assertErr(t, err)
634 result := "{\n-\t\"a\": 1,\n-\t\"b\": 2.1,\n-\t\"c\": {\n-\t\t\"E\": 10,\n-\t\t\"F\": 11\n-\t},\n-\t\"d\": 4\n-}"
635 assertEq(t, "map[string]any", result, string(bytes))
636 })
637 })
638 }
639
640 type StringTag struct {
641 BoolStr bool `json:",string"`
642 IntStr int64 `json:",string"`
643 UintptrStr uintptr `json:",string"`
644 StrStr string `json:",string"`
645 NumberStr json.Number `json:",string"`
646 }
647
648 func TestRoundtripStringTag(t *testing.T) {
649 tests := []struct {
650 name string
651 in StringTag
652 want string // empty to just test that we roundtrip
653 }{
654 {
655 name: "AllTypes",
656 in: StringTag{
657 BoolStr: true,
658 IntStr: 42,
659 UintptrStr: 44,
660 StrStr: "xzbit",
661 NumberStr: "46",
662 },
663 want: `{
664 "BoolStr": "true",
665 "IntStr": "42",
666 "UintptrStr": "44",
667 "StrStr": "\"xzbit\"",
668 "NumberStr": "46"
669 }`,
670 },
671 {
672 // See golang.org/issues/38173.
673 name: "StringDoubleEscapes",
674 in: StringTag{
675 StrStr: "\b\f\n\r\t\"\\",
676 NumberStr: "0", // just to satisfy the roundtrip
677 },
678 },
679 }
680 for _, test := range tests {
681 t.Run(test.name, func(t *testing.T) {
682 // Indent with a tab prefix to make the multi-line string
683 // literals in the table nicer to read.
684 got, err := json.MarshalIndent(&test.in, "\t\t\t", "\t")
685 if err != nil {
686 t.Fatal(err)
687 }
688 if got := string(got); test.want != "" && got != test.want {
689 t.Fatalf(" got: %s\nwant: %s\n", got, test.want)
690 }
691 // the escapes are the ones of encoding/json of the Go version: \b and \f are escaped by their code
692 // before Go 1.22
693 if want, _ := stdjson.MarshalIndent(&test.in, "\t\t\t", "\t"); string(got) != string(want) {
694 t.Fatalf(" got: %s\nwant: %s\n", got, want)
695 }
696
697 // Verify that it round-trips.
698 var s2 StringTag
699 if err := json.Unmarshal(got, &s2); err != nil {
700 t.Fatalf("Decode: %v", err)
701 }
702 if !reflect.DeepEqual(test.in, s2) {
703 t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", test.in, string(got), s2)
704 }
705 })
706 }
707 }
708
709 // byte slices are special even if they're renamed types.
710 type renamedByte byte
711 type renamedByteSlice []byte
712 type renamedRenamedByteSlice []renamedByte
713
714 func TestEncodeRenamedByteSlice(t *testing.T) {
715 s := renamedByteSlice("abc")
716 result, err := json.Marshal(s)
717 if err != nil {
718 t.Fatal(err)
719 }
720 expect := `"YWJj"`
721 if string(result) != expect {
722 t.Errorf(" got %s want %s", result, expect)
723 }
724 r := renamedRenamedByteSlice("abc")
725 result, err = json.Marshal(r)
726 if err != nil {
727 t.Fatal(err)
728 }
729 if string(result) != expect {
730 t.Errorf(" got %s want %s", result, expect)
731 }
732 }
733
734 func TestMarshalRawMessageValue(t *testing.T) {
735 type (
736 T1 struct {
737 M json.RawMessage `json:",omitempty"`
738 }
739 T2 struct {
740 M *json.RawMessage `json:",omitempty"`
741 }
742 )
743
744 var (
745 rawNil = json.RawMessage(nil)
746 rawEmpty = json.RawMessage([]byte{})
747 rawText = json.RawMessage([]byte(`"foo"`))
748 )
749
750 tests := []struct {
751 in any
752 want string
753 ok bool
754 }{
755 // Test with nil RawMessage.
756 {rawNil, "null", true},
757 {&rawNil, "null", true},
758 {[]any{rawNil}, "[null]", true},
759 {&[]any{rawNil}, "[null]", true},
760 {[]any{&rawNil}, "[null]", true},
761 {&[]any{&rawNil}, "[null]", true},
762 {struct{ M json.RawMessage }{rawNil}, `{"M":null}`, true},
763 {&struct{ M json.RawMessage }{rawNil}, `{"M":null}`, true},
764 {struct{ M *json.RawMessage }{&rawNil}, `{"M":null}`, true},
765 {&struct{ M *json.RawMessage }{&rawNil}, `{"M":null}`, true},
766 {map[string]any{"M": rawNil}, `{"M":null}`, true},
767 {&map[string]any{"M": rawNil}, `{"M":null}`, true},
768 {map[string]any{"M": &rawNil}, `{"M":null}`, true},
769 {&map[string]any{"M": &rawNil}, `{"M":null}`, true},
770 {T1{rawNil}, "{}", true},
771 {T2{&rawNil}, `{"M":null}`, true},
772 {&T1{rawNil}, "{}", true},
773 {&T2{&rawNil}, `{"M":null}`, true},
774
775 // Test with empty, but non-nil, RawMessage.
776 {rawEmpty, "", false},
777 {&rawEmpty, "", false},
778 {[]any{rawEmpty}, "", false},
779 {&[]any{rawEmpty}, "", false},
780 {[]any{&rawEmpty}, "", false},
781 {&[]any{&rawEmpty}, "", false},
782 {struct{ X json.RawMessage }{rawEmpty}, "", false},
783 {&struct{ X json.RawMessage }{rawEmpty}, "", false},
784 {struct{ X *json.RawMessage }{&rawEmpty}, "", false},
785 {&struct{ X *json.RawMessage }{&rawEmpty}, "", false},
786 {map[string]any{"nil": rawEmpty}, "", false},
787 {&map[string]any{"nil": rawEmpty}, "", false},
788 {map[string]any{"nil": &rawEmpty}, "", false},
789 {&map[string]any{"nil": &rawEmpty}, "", false},
790
791 {T1{rawEmpty}, "{}", true},
792 {T2{&rawEmpty}, "", false},
793 {&T1{rawEmpty}, "{}", true},
794 {&T2{&rawEmpty}, "", false},
795
796 // Test with RawMessage with some text.
797 //
798 // The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo".
799 // This behavior was intentionally changed in Go 1.8.
800 // See https://golang.org/issues/14493#issuecomment-255857318
801 {rawText, `"foo"`, true}, // Issue6458
802 {&rawText, `"foo"`, true},
803 {[]any{rawText}, `["foo"]`, true}, // Issue6458
804 {&[]any{rawText}, `["foo"]`, true}, // Issue6458
805 {[]any{&rawText}, `["foo"]`, true},
806 {&[]any{&rawText}, `["foo"]`, true},
807 {struct{ M json.RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458
808 {&struct{ M json.RawMessage }{rawText}, `{"M":"foo"}`, true},
809 {struct{ M *json.RawMessage }{&rawText}, `{"M":"foo"}`, true},
810 {&struct{ M *json.RawMessage }{&rawText}, `{"M":"foo"}`, true},
811 {map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
812 {&map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
813 {map[string]any{"M": &rawText}, `{"M":"foo"}`, true},
814 {&map[string]any{"M": &rawText}, `{"M":"foo"}`, true},
815 {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458
816 {T2{&rawText}, `{"M":"foo"}`, true},
817 {&T1{rawText}, `{"M":"foo"}`, true},
818 {&T2{&rawText}, `{"M":"foo"}`, true},
819 }
820
821 for i, tt := range tests {
822 b, err := json.Marshal(tt.in)
823 if ok := (err == nil); ok != tt.ok {
824 if err != nil {
825 t.Errorf("test %d, unexpected failure: %v", i, err)
826 } else {
827 t.Errorf("test %d, unexpected success", i)
828 }
829 }
830 if got := string(b); got != tt.want {
831 t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want)
832 }
833 }
834 }
835
836 type marshalerError struct{}
837
838 func (*marshalerError) MarshalJSON() ([]byte, error) {
839 return nil, errors.New("unexpected error")
840 }
841
842 func Test_MarshalerError(t *testing.T) {
843 var v marshalerError
844 _, err := json.Marshal(&v)
845 expect := `json: error calling MarshalJSON for type *json_test.marshalerError: unexpected error`
846 assertEq(t, "marshaler error", expect, fmt.Sprint(err))
847 }
848
849 // Ref has Marshaler and Unmarshaler methods with pointer receiver.
850 type Ref int
851
852 func (*Ref) MarshalJSON() ([]byte, error) {
853 return []byte(`"ref"`), nil
854 }
855
856 func (r *Ref) UnmarshalJSON([]byte) error {
857 *r = 12
858 return nil
859 }
860
861 // Val has Marshaler methods with value receiver.
862 type Val int
863
864 func (Val) MarshalJSON() ([]byte, error) {
865 return []byte(`"val"`), nil
866 }
867
868 // RefText has Marshaler and Unmarshaler methods with pointer receiver.
869 type RefText int
870
871 func (*RefText) MarshalText() ([]byte, error) {
872 return []byte(`"ref"`), nil
873 }
874
875 func (r *RefText) UnmarshalText([]byte) error {
876 *r = 13
877 return nil
878 }
879
880 // ValText has Marshaler methods with value receiver.
881 type ValText int
882
883 func (ValText) MarshalText() ([]byte, error) {
884 return []byte(`"val"`), nil
885 }
886
887 func TestRefValMarshal(t *testing.T) {
888 var s = struct {
889 R0 Ref
890 R1 *Ref
891 R2 RefText
892 R3 *RefText
893 V0 Val
894 V1 *Val
895 V2 ValText
896 V3 *ValText
897 }{
898 R0: 12,
899 R1: new(Ref),
900 R2: 14,
901 R3: new(RefText),
902 V0: 13,
903 V1: new(Val),
904 V2: 15,
905 V3: new(ValText),
906 }
907 const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}`
908 b, err := json.Marshal(&s)
909 if err != nil {
910 t.Fatalf("Marshal: %v", err)
911 }
912 if got := string(b); got != want {
913 t.Errorf("got %q, want %q", got, want)
914 }
915 }
916
917 // C implements Marshaler and returns unescaped JSON.
918 type C int
919
920 func (C) MarshalJSON() ([]byte, error) {
921 return []byte(`"<&>"`), nil
922 }
923
924 // CText implements Marshaler and returns unescaped text.
925 type CText int
926
927 func (CText) MarshalText() ([]byte, error) {
928 return []byte(`"<&>"`), nil
929 }
930
931 func TestMarshalerEscaping(t *testing.T) {
932 var c C
933 want := `"\u003c\u0026\u003e"`
934 b, err := json.Marshal(c)
935 if err != nil {
936 t.Fatalf("Marshal(c): %v", err)
937 }
938 if got := string(b); got != want {
939 t.Errorf("Marshal(c) = %#q, want %#q", got, want)
940 }
941
942 var ct CText
943 want = `"\"\u003c\u0026\u003e\""`
944 b, err = json.Marshal(ct)
945 if err != nil {
946 t.Fatalf("Marshal(ct): %v", err)
947 }
948 if got := string(b); got != want {
949 t.Errorf("Marshal(ct) = %#q, want %#q", got, want)
950 }
951 }
952
953 type marshalPanic struct{}
954
955 func (marshalPanic) MarshalJSON() ([]byte, error) { panic(0xdead) }
956
957 func TestMarshalPanic(t *testing.T) {
958 defer func() {
959 if got := recover(); !reflect.DeepEqual(got, 0xdead) {
960 t.Errorf("panic() = (%T)(%v), want 0xdead", got, got)
961 }
962 }()
963 json.Marshal(&marshalPanic{})
964 t.Error("Marshal should have panicked")
965 }
966
967 func TestMarshalUncommonFieldNames(t *testing.T) {
968 v := struct {
969 A0, À, Aβ int
970 }{}
971 b, err := json.Marshal(v)
972 if err != nil {
973 t.Fatal("Marshal:", err)
974 }
975 want := `{"A0":0,"À":0,"Aβ":0}`
976 got := string(b)
977 if got != want {
978 t.Fatalf("Marshal: got %s want %s", got, want)
979 }
980 }
981
982 func TestMarshalerError(t *testing.T) {
983 s := "test variable"
984 st := reflect.TypeOf(s)
985 errText := "json: test error"
986
987 tests := []struct {
988 err *json.MarshalerError
989 want string
990 }{
991 {
992 json.NewMarshalerError(st, fmt.Errorf(errText), ""),
993 "json: error calling MarshalJSON for type " + st.String() + ": " + errText,
994 },
995 {
996 json.NewMarshalerError(st, fmt.Errorf(errText), "TestMarshalerError"),
997 "json: error calling TestMarshalerError for type " + st.String() + ": " + errText,
998 },
999 }
1000
1001 for i, tt := range tests {
1002 got := tt.err.Error()
1003 if got != tt.want {
1004 t.Errorf("MarshalerError test %d, got: %s, want: %s", i, got, tt.want)
1005 }
1006 }
1007 }
1008
1009 type unmarshalerText struct {
1010 A, B string
1011 }
1012
1013 // needed for re-marshaling tests
1014 func (u unmarshalerText) MarshalText() ([]byte, error) {
1015 return []byte(u.A + ":" + u.B), nil
1016 }
1017
1018 func (u *unmarshalerText) UnmarshalText(b []byte) error {
1019 before, after, ok := bytes.Cut(b, []byte{':'})
1020 if !ok {
1021 return errors.New("missing separator")
1022 }
1023 u.A, u.B = string(before), string(after)
1024 return nil
1025 }
1026
1027 func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
1028 data := map[unmarshalerText]int{
1029 {"x", "y"}: 1,
1030 {"y", "x"}: 2,
1031 {"a", "z"}: 3,
1032 {"z", "a"}: 4,
1033 }
1034 b, err := json.Marshal(data)
1035 if err != nil {
1036 t.Fatalf("Failed to Marshal text.Marshaler: %v", err)
1037 }
1038 const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}`
1039 if string(b) != want {
1040 t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want)
1041 }
1042
1043 b, err = stdjson.Marshal(data)
1044 if err != nil {
1045 t.Fatalf("Failed to std Marshal text.Marshaler: %v", err)
1046 }
1047 if string(b) != want {
1048 t.Errorf("std Marshal map with text.Marshaler keys: got %#q, want %#q", b, want)
1049 }
1050 }
1051
1052 // https://golang.org/issue/33675
1053 func TestNilMarshalerTextMapKey(t *testing.T) {
1054 v := map[*unmarshalerText]int{
1055 (*unmarshalerText)(nil): 1,
1056 {"A", "B"}: 2,
1057 }
1058 b, err := json.Marshal(v)
1059 if err != nil {
1060 t.Fatalf("Failed to Marshal *text.Marshaler: %v", err)
1061 }
1062 const want = `{"":1,"A:B":2}`
1063 if string(b) != want {
1064 t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want)
1065 }
1066 }
1067
1068 var re = regexp.MustCompile
1069
1070 // syntactic checks on form of marshaled floating point numbers.
1071 var badFloatREs = []*regexp.Regexp{
1072 re(`p`), // no binary exponential notation
1073 re(`^\+`), // no leading + sign
1074 re(`^-?0[^.]`), // no unnecessary leading zeros
1075 re(`^-?\.`), // leading zero required before decimal point
1076 re(`\.(e|$)`), // no trailing decimal
1077 re(`\.[0-9]+0(e|$)`), // no trailing zero in fraction
1078 re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa
1079 re(`e[0-9]`), // positive exponent must be signed
1080 re(`e[+-]0`), // exponent must not have leading zeros
1081 re(`e-[1-6]$`), // not tiny enough for exponential notation
1082 re(`e+(.|1.|20)$`), // not big enough for exponential notation
1083 re(`^-?0\.0000000`), // too tiny, should use exponential notation
1084 re(`^-?[0-9]{22}`), // too big, should use exponential notation
1085 re(`[1-9][0-9]{16}[1-9]`), // too many significant digits in integer
1086 re(`[1-9][0-9.]{17}[1-9]`), // too many significant digits in decimal
1087 // below here for float32 only
1088 re(`[1-9][0-9]{8}[1-9]`), // too many significant digits in integer
1089 re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal
1090 }
1091
1092 func TestMarshalFloat(t *testing.T) {
1093 //t.Parallel()
1094 nfail := 0
1095 test := func(f float64, bits int) {
1096 vf := any(f)
1097 if bits == 32 {
1098 f = float64(float32(f)) // round
1099 vf = float32(f)
1100 }
1101 bout, err := json.Marshal(vf)
1102 if err != nil {
1103 t.Errorf("Marshal(%T(%g)): %v", vf, vf, err)
1104 nfail++
1105 return
1106 }
1107 out := string(bout)
1108
1109 // result must convert back to the same float
1110 g, err := strconv.ParseFloat(out, bits)
1111 if err != nil {
1112 t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err)
1113 nfail++
1114 return
1115 }
1116 if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0
1117 t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf)
1118 nfail++
1119 return
1120 }
1121
1122 bad := badFloatREs
1123 if bits == 64 {
1124 bad = bad[:len(bad)-2]
1125 }
1126 for _, re := range bad {
1127 if re.MatchString(out) {
1128 t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re)
1129 nfail++
1130 return
1131 }
1132 }
1133 }
1134
1135 var (
1136 bigger = math.Inf(+1)
1137 smaller = math.Inf(-1)
1138 )
1139
1140 var digits = "1.2345678901234567890123"
1141 for i := len(digits); i >= 2; i-- {
1142 if testing.Short() && i < len(digits)-4 {
1143 break
1144 }
1145 for exp := -30; exp <= 30; exp++ {
1146 for _, sign := range "+-" {
1147 for bits := 32; bits <= 64; bits += 32 {
1148 s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp)
1149 f, err := strconv.ParseFloat(s, bits)
1150 if err != nil {
1151 log.Fatal(err)
1152 }
1153 next := math.Nextafter
1154 if bits == 32 {
1155 next = func(g, h float64) float64 {
1156 return float64(math.Nextafter32(float32(g), float32(h)))
1157 }
1158 }
1159 test(f, bits)
1160 test(next(f, bigger), bits)
1161 test(next(f, smaller), bits)
1162 if nfail > 50 {
1163 t.Fatalf("stopping test early")
1164 }
1165 }
1166 }
1167 }
1168 }
1169 test(0, 64)
1170 test(math.Copysign(0, -1), 64)
1171 test(0, 32)
1172 test(math.Copysign(0, -1), 32)
1173 }
1174
1175 // encodeStringTests are the control characters, which are escaped as encoding/json of the Go version escapes them:
1176 // \b and \f are escaped by their code before Go 1.22.
1177 var encodeStringTests = []string{
1178 "\x00",
1179 "\x01",
1180 "\x02",
1181 "\x03",
1182 "\x04",
1183 "\x05",
1184 "\x06",
1185 "\x07",
1186 "\x08",
1187 "\x09",
1188 "\x0a",
1189 "\x0b",
1190 "\x0c",
1191 "\x0d",
1192 "\x0e",
1193 "\x0f",
1194 "\x10",
1195 "\x11",
1196 "\x12",
1197 "\x13",
1198 "\x14",
1199 "\x15",
1200 "\x16",
1201 "\x17",
1202 "\x18",
1203 "\x19",
1204 "\x1a",
1205 "\x1b",
1206 "\x1c",
1207 "\x1d",
1208 "\x1e",
1209 "\x1f",
1210 }
1211
1212 func TestEncodeString(t *testing.T) {
1213 for _, in := range encodeStringTests {
1214 b, err := json.Marshal(in)
1215 if err != nil {
1216 t.Errorf("Marshal(%q): %v", in, err)
1217 continue
1218 }
1219 want, _ := stdjson.Marshal(in)
1220 if out := string(b); out != string(want) {
1221 t.Errorf("Marshal(%q) = %#q, want %#q", in, out, want)
1222 }
1223 }
1224 }
1225
1226 type jsonbyte byte
1227
1228 func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) }
1229
1230 type textbyte byte
1231
1232 func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) }
1233
1234 type jsonint int
1235
1236 func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) }
1237
1238 type textint int
1239
1240 func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) }
1241
1242 func tenc(format string, a ...any) ([]byte, error) {
1243 var buf bytes.Buffer
1244 fmt.Fprintf(&buf, format, a...)
1245 return buf.Bytes(), nil
1246 }
1247
1248 // Issue 13783
1249 func TestEncodeBytekind(t *testing.T) {
1250 testdata := []struct {
1251 data any
1252 want string
1253 }{
1254 {byte(7), "7"},
1255 {jsonbyte(7), `{"JB":7}`},
1256 {textbyte(4), `"TB:4"`},
1257 {jsonint(5), `{"JI":5}`},
1258 {textint(1), `"TI:1"`},
1259 {[]byte{0, 1}, `"AAE="`},
1260
1261 {[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`},
1262 {[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`},
1263 {[]textbyte{2, 3}, `["TB:2","TB:3"]`},
1264
1265 {[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`},
1266 {[]textint{9, 3}, `["TI:9","TI:3"]`},
1267 {[]int{9, 3}, `[9,3]`},
1268 }
1269 for i, d := range testdata {
1270 js, err := json.Marshal(d.data)
1271 if err != nil {
1272 t.Error(err)
1273 continue
1274 }
1275 got, want := string(js), d.want
1276 if got != want {
1277 t.Errorf("%d: got %s, want %s", i, got, want)
1278 }
1279 }
1280 }
1281
1282 // golang.org/issue/8582
1283 func TestEncodePointerString(t *testing.T) {
1284 type stringPointer struct {
1285 N *int64 `json:"n,string"`
1286 }
1287 var n int64 = 42
1288 b, err := json.Marshal(stringPointer{N: &n})
1289 if err != nil {
1290 t.Fatalf("Marshal: %v", err)
1291 }
1292 if got, want := string(b), `{"n":"42"}`; got != want {
1293 t.Errorf("Marshal = %s, want %s", got, want)
1294 }
1295 var back stringPointer
1296 err = json.Unmarshal(b, &back)
1297 if err != nil {
1298 t.Fatalf("Unmarshal: %v", err)
1299 }
1300 if back.N == nil {
1301 t.Fatalf("Unmarshaled nil N field")
1302 }
1303 if *back.N != 42 {
1304 t.Fatalf("*N = %d; want 42", *back.N)
1305 }
1306 }
1307
1308 type SamePointerNoCycle struct {
1309 Ptr1, Ptr2 *SamePointerNoCycle
1310 }
1311
1312 var samePointerNoCycle = &SamePointerNoCycle{}
1313
1314 type PointerCycle struct {
1315 Ptr *PointerCycle
1316 }
1317
1318 var pointerCycle = &PointerCycle{}
1319
1320 type PointerCycleIndirect struct {
1321 Ptrs []any
1322 }
1323
1324 var pointerCycleIndirect = &PointerCycleIndirect{}
1325
1326 func init() {
1327 ptr := &SamePointerNoCycle{}
1328 samePointerNoCycle.Ptr1 = ptr
1329 samePointerNoCycle.Ptr2 = ptr
1330
1331 pointerCycle.Ptr = pointerCycle
1332 pointerCycleIndirect.Ptrs = []any{pointerCycleIndirect}
1333 }
1334
1335 func TestSamePointerNoCycle(t *testing.T) {
1336 if _, err := json.Marshal(samePointerNoCycle); err != nil {
1337 t.Fatalf("unexpected error: %v", err)
1338 }
1339 }
1340
1341 var unsupportedValues = []any{
1342 math.NaN(),
1343 math.Inf(-1),
1344 math.Inf(1),
1345 float32(math.NaN()),
1346 float32(math.Inf(-1)),
1347 float32(math.Inf(1)),
1348 struct{ F float32 }{float32(math.Inf(1))},
1349 struct {
1350 F float32 `json:",omitempty"`
1351 }{float32(math.NaN())},
1352 struct{ F *float32 }{func() *float32 { f := float32(math.Inf(1)); return &f }()},
1353 struct {
1354 F float32 `json:",string"`
1355 }{float32(math.Inf(-1))},
1356 []float32{float32(math.NaN())},
1357 map[string]float32{"a": float32(math.Inf(1))},
1358 []any{float32(math.Inf(1))},
1359 pointerCycle,
1360 pointerCycleIndirect,
1361 }
1362
1363 func TestUnsupportedValues(t *testing.T) {
1364 for _, v := range unsupportedValues {
1365 if _, err := json.Marshal(v); err != nil {
1366 if _, ok := err.(*json.UnsupportedValueError); !ok {
1367 t.Errorf("for %v, got %T want UnsupportedValueError", v, err)
1368 }
1369 } else {
1370 t.Errorf("for %v, expected error", v)
1371 }
1372 if _, err := json.MarshalIndent(v, "", " "); err == nil {
1373 t.Errorf("for %v with indent, expected error", v)
1374 }
1375 }
1376 }
1377
1378 func TestIssue10281(t *testing.T) {
1379 type Foo struct {
1380 N json.Number
1381 }
1382 x := Foo{json.Number(`invalid`)}
1383
1384 b, err := json.Marshal(&x)
1385 if err == nil {
1386 t.Errorf("Marshal(&x) = %#q; want error", b)
1387 }
1388 }
1389
1390 func TestHTMLEscape(t *testing.T) {
1391 var b, want bytes.Buffer
1392 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}`
1393 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`))
1394 json.HTMLEscape(&b, []byte(m))
1395 if !bytes.Equal(b.Bytes(), want.Bytes()) {
1396 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes())
1397 }
1398 }
1399
1400 type BugA struct {
1401 S string
1402 }
1403
1404 type BugB struct {
1405 BugA
1406 S string
1407 }
1408
1409 type BugC struct {
1410 S string
1411 }
1412
1413 // Legal Go: We never use the repeated embedded field (S).
1414 type BugX struct {
1415 A int
1416 BugA
1417 BugB
1418 }
1419
1420 // golang.org/issue/16042.
1421 // Even if a nil interface value is passed in, as long as
1422 // it implements Marshaler, it should be marshaled.
1423 type nilJSONMarshaler string
1424
1425 func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) {
1426 if nm == nil {
1427 return json.Marshal("0zenil0")
1428 }
1429 return json.Marshal("zenil:" + string(*nm))
1430 }
1431
1432 // golang.org/issue/34235.
1433 // Even if a nil interface value is passed in, as long as
1434 // it implements encoding.TextMarshaler, it should be marshaled.
1435 type nilTextMarshaler string
1436
1437 func (nm *nilTextMarshaler) MarshalText() ([]byte, error) {
1438 if nm == nil {
1439 return []byte("0zenil0"), nil
1440 }
1441 return []byte("zenil:" + string(*nm)), nil
1442 }
1443
1444 // See golang.org/issue/16042 and golang.org/issue/34235.
1445 func TestNilMarshal(t *testing.T) {
1446 testCases := []struct {
1447 v any
1448 want string
1449 }{
1450 {v: nil, want: `null`},
1451 {v: new(float64), want: `0`},
1452 {v: []any(nil), want: `null`},
1453 {v: []string(nil), want: `null`},
1454 {v: map[string]string(nil), want: `null`},
1455 {v: []byte(nil), want: `null`},
1456 {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`},
1457 {v: struct{ M json.Marshaler }{}, want: `{"M":null}`},
1458 {v: struct{ M json.Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
1459 {v: struct{ M any }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`},
1460 {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`},
1461 {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
1462 {v: struct{ M any }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`},
1463 }
1464
1465 for i, tt := range testCases {
1466 out, err := json.Marshal(tt.v)
1467 if err != nil || string(out) != tt.want {
1468 t.Errorf("%d: Marshal(%#v) = %#q, %#v, want %#q, nil", i, tt.v, out, err, tt.want)
1469 continue
1470 }
1471 }
1472 }
1473
1474 // Issue 5245.
1475 func TestEmbeddedBug(t *testing.T) {
1476 v := BugB{
1477 BugA{"A"},
1478 "B",
1479 }
1480 b, err := json.Marshal(v)
1481 if err != nil {
1482 t.Fatal("Marshal:", err)
1483 }
1484 want := `{"S":"B"}`
1485 got := string(b)
1486 if got != want {
1487 t.Fatalf("Marshal: got %s want %s", got, want)
1488 }
1489 // Now check that the duplicate field, S, does not appear.
1490 x := BugX{
1491 A: 23,
1492 }
1493 b, err = json.Marshal(x)
1494 if err != nil {
1495 t.Fatal("Marshal:", err)
1496 }
1497 want = `{"A":23}`
1498 got = string(b)
1499 if got != want {
1500 t.Fatalf("Marshal: got %s want %s", got, want)
1501 }
1502 }
1503
1504 type BugD struct { // Same as BugA after tagging.
1505 XXX string `json:"S"`
1506 }
1507
1508 // BugD's tagged S field should dominate BugA's.
1509 type BugY struct {
1510 BugA
1511 BugD
1512 }
1513
1514 // Test that a field with a tag dominates untagged fields.
1515 func TestTaggedFieldDominates(t *testing.T) {
1516 v := BugY{
1517 BugA{"BugA"},
1518 BugD{"BugD"},
1519 }
1520 b, err := json.Marshal(v)
1521 if err != nil {
1522 t.Fatal("Marshal:", err)
1523 }
1524 want := `{"S":"BugD"}`
1525 got := string(b)
1526 if got != want {
1527 t.Fatalf("Marshal: got %s want %s", got, want)
1528 }
1529 }
1530
1531 // There are no tags here, so S should not appear.
1532 type BugZ struct {
1533 BugA
1534 BugC
1535 BugY // Contains a tagged S field through BugD; should not dominate.
1536 }
1537
1538 func TestDuplicatedFieldDisappears(t *testing.T) {
1539 v := BugZ{
1540 BugA{"BugA"},
1541 BugC{"BugC"},
1542 BugY{
1543 BugA{"nested BugA"},
1544 BugD{"nested BugD"},
1545 },
1546 }
1547 b, err := json.Marshal(v)
1548 if err != nil {
1549 t.Fatal("Marshal:", err)
1550 }
1551 want := `{}`
1552 got := string(b)
1553 if got != want {
1554 t.Fatalf("Marshal: got %s want %s", got, want)
1555 }
1556 }
1557
1558 func TestAnonymousFields(t *testing.T) {
1559 tests := []struct {
1560 label string // Test name
1561 makeInput func() any // Function to create input value
1562 want string // Expected JSON output
1563 }{{
1564 // Both S1 and S2 have a field named X. From the perspective of S,
1565 // it is ambiguous which one X refers to.
1566 // This should not serialize either field.
1567 label: "AmbiguousField",
1568 makeInput: func() any {
1569 type (
1570 S1 struct{ x, X int }
1571 S2 struct{ x, X int }
1572 S struct {
1573 S1
1574 S2
1575 }
1576 )
1577 return S{S1{1, 2}, S2{3, 4}}
1578 },
1579 want: `{}`,
1580 }, {
1581 label: "DominantField",
1582 // Both S1 and S2 have a field named X, but since S has an X field as
1583 // well, it takes precedence over S1.X and S2.X.
1584 makeInput: func() any {
1585 type (
1586 S1 struct{ x, X int }
1587 S2 struct{ x, X int }
1588 S struct {
1589 S1
1590 S2
1591 x, X int
1592 }
1593 )
1594 return S{S1{1, 2}, S2{3, 4}, 5, 6}
1595 },
1596 want: `{"X":6}`,
1597 }, {
1598 // Unexported embedded field of non-struct type should not be serialized.
1599 label: "UnexportedEmbeddedInt",
1600 makeInput: func() any {
1601 type (
1602 myInt int
1603 S struct{ myInt }
1604 )
1605 return S{5}
1606 },
1607 want: `{}`,
1608 }, {
1609 // Exported embedded field of non-struct type should be serialized.
1610 label: "ExportedEmbeddedInt",
1611 makeInput: func() any {
1612 type (
1613 MyInt int
1614 S struct{ MyInt }
1615 )
1616 return S{5}
1617 },
1618 want: `{"MyInt":5}`,
1619 }, {
1620 // Unexported embedded field of pointer to non-struct type
1621 // should not be serialized.
1622 label: "UnexportedEmbeddedIntPointer",
1623 makeInput: func() any {
1624 type (
1625 myInt int
1626 S struct{ *myInt }
1627 )
1628 s := S{new(myInt)}
1629 *s.myInt = 5
1630 return s
1631 },
1632 want: `{}`,
1633 }, {
1634 // Exported embedded field of pointer to non-struct type
1635 // should be serialized.
1636 label: "ExportedEmbeddedIntPointer",
1637 makeInput: func() any {
1638 type (
1639 MyInt int
1640 S struct{ *MyInt }
1641 )
1642 s := S{new(MyInt)}
1643 *s.MyInt = 5
1644 return s
1645 },
1646 want: `{"MyInt":5}`,
1647 }, {
1648 // Exported fields of embedded structs should have their
1649 // exported fields be serialized regardless of whether the struct types
1650 // themselves are exported.
1651 label: "EmbeddedStruct",
1652 makeInput: func() any {
1653 type (
1654 s1 struct{ x, X int }
1655 S2 struct{ y, Y int }
1656 S struct {
1657 s1
1658 S2
1659 }
1660 )
1661 return S{s1{1, 2}, S2{3, 4}}
1662 },
1663 want: `{"X":2,"Y":4}`,
1664 }, {
1665 // Exported fields of pointers to embedded structs should have their
1666 // exported fields be serialized regardless of whether the struct types
1667 // themselves are exported.
1668 label: "EmbeddedStructPointer",
1669 makeInput: func() any {
1670 type (
1671 s1 struct{ x, X int }
1672 S2 struct{ y, Y int }
1673 S struct {
1674 *s1
1675 *S2
1676 }
1677 )
1678 return S{&s1{1, 2}, &S2{3, 4}}
1679 },
1680 want: `{"X":2,"Y":4}`,
1681 }, {
1682 // Exported fields on embedded unexported structs at multiple levels
1683 // of nesting should still be serialized.
1684 label: "NestedStructAndInts",
1685 makeInput: func() any {
1686 type (
1687 MyInt1 int
1688 MyInt2 int
1689 myInt int
1690 s2 struct {
1691 MyInt2
1692 myInt
1693 }
1694 s1 struct {
1695 MyInt1
1696 myInt
1697 s2
1698 }
1699 S struct {
1700 s1
1701 myInt
1702 }
1703 )
1704 return S{s1{1, 2, s2{3, 4}}, 6}
1705 },
1706 want: `{"MyInt1":1,"MyInt2":3}`,
1707 }, {
1708 // If an anonymous struct pointer field is nil, we should ignore
1709 // the embedded fields behind it. Not properly doing so may
1710 // result in the wrong output or reflect panics.
1711 label: "EmbeddedFieldBehindNilPointer",
1712 makeInput: func() any {
1713 type (
1714 S2 struct{ Field string }
1715 S struct{ *S2 }
1716 )
1717 return S{}
1718 },
1719 want: `{}`,
1720 }}
1721
1722 for i, tt := range tests {
1723 t.Run(tt.label, func(t *testing.T) {
1724 b, err := json.Marshal(tt.makeInput())
1725 if err != nil {
1726 t.Fatalf("%d: Marshal() = %v, want nil error", i, err)
1727 }
1728 if string(b) != tt.want {
1729 t.Fatalf("%d: Marshal() = %q, want %q", i, b, tt.want)
1730 }
1731 })
1732 }
1733 }
1734
1735 type Optionals struct {
1736 Sr string `json:"sr"`
1737 So string `json:"so,omitempty"`
1738 Sw string `json:"-"`
1739
1740 Ir int `json:"omitempty"` // actually named omitempty, not an option
1741 Io int `json:"io,omitempty"`
1742
1743 Slr []string `json:"slr,random"`
1744 Slo []string `json:"slo,omitempty"`
1745
1746 Mr map[string]any `json:"mr"`
1747 Mo map[string]any `json:",omitempty"`
1748
1749 Fr float64 `json:"fr"`
1750 Fo float64 `json:"fo,omitempty"`
1751
1752 Br bool `json:"br"`
1753 Bo bool `json:"bo,omitempty"`
1754
1755 Ur uint `json:"ur"`
1756 Uo uint `json:"uo,omitempty"`
1757
1758 Str struct{} `json:"str"`
1759 Sto struct{} `json:"sto,omitempty"`
1760 }
1761
1762 var optionalsExpected = `{
1763 "sr": "",
1764 "omitempty": 0,
1765 "slr": null,
1766 "mr": {},
1767 "fr": 0,
1768 "br": false,
1769 "ur": 0,
1770 "str": {},
1771 "sto": {}
1772 }`
1773
1774 func TestOmitEmpty(t *testing.T) {
1775 var o Optionals
1776 o.Sw = "something"
1777 o.Mr = map[string]any{}
1778 o.Mo = map[string]any{}
1779
1780 got, err := json.MarshalIndent(&o, "", " ")
1781 if err != nil {
1782 t.Fatal(err)
1783 }
1784 if got := string(got); got != optionalsExpected {
1785 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected)
1786 }
1787 }
1788
1789 type testNullStr string
1790
1791 func (v *testNullStr) MarshalJSON() ([]byte, error) {
1792 if *v == "" {
1793 return []byte("null"), nil
1794 }
1795
1796 return []byte(*v), nil
1797 }
1798
1799 func TestIssue147(t *testing.T) {
1800 type T struct {
1801 Field1 string `json:"field1"`
1802 Field2 testNullStr `json:"field2,omitempty"`
1803 }
1804 got, err := json.Marshal(T{
1805 Field1: "a",
1806 Field2: "b",
1807 })
1808 if err != nil {
1809 t.Fatal(err)
1810 }
1811 expect, _ := stdjson.Marshal(T{
1812 Field1: "a",
1813 Field2: "b",
1814 })
1815 if !bytes.Equal(expect, got) {
1816 t.Fatalf("expect %q but got %q", string(expect), string(got))
1817 }
1818 }
1819
1820 type testIssue144 struct {
1821 name string
1822 number int64
1823 }
1824
1825 func (v *testIssue144) MarshalJSON() ([]byte, error) {
1826 if v.name != "" {
1827 return json.Marshal(v.name)
1828 }
1829 return json.Marshal(v.number)
1830 }
1831
1832 func TestIssue144(t *testing.T) {
1833 type Embeded struct {
1834 Field *testIssue144 `json:"field,omitempty"`
1835 }
1836 type T struct {
1837 Embeded
1838 }
1839 {
1840 v := T{
1841 Embeded: Embeded{Field: &testIssue144{name: "hoge"}},
1842 }
1843 got, err := json.Marshal(v)
1844 if err != nil {
1845 t.Fatal(err)
1846 }
1847 expect, _ := stdjson.Marshal(v)
1848 if !bytes.Equal(expect, got) {
1849 t.Fatalf("expect %q but got %q", string(expect), string(got))
1850 }
1851 }
1852 {
1853 v := &T{
1854 Embeded: Embeded{Field: &testIssue144{name: "hoge"}},
1855 }
1856 got, err := json.Marshal(v)
1857 if err != nil {
1858 t.Fatal(err)
1859 }
1860 expect, _ := stdjson.Marshal(v)
1861 if !bytes.Equal(expect, got) {
1862 t.Fatalf("expect %q but got %q", string(expect), string(got))
1863 }
1864 }
1865 }
1866
1867 func TestIssue118(t *testing.T) {
1868 type data struct {
1869 Columns []string `json:"columns"`
1870 Rows1 [][]string `json:"rows1"`
1871 Rows2 [][]string `json:"rows2"`
1872 }
1873 v := data{Columns: []string{"1", "2", "3"}}
1874 got, err := json.MarshalIndent(v, "", " ")
1875 if err != nil {
1876 t.Fatal(err)
1877 }
1878 expect, _ := stdjson.MarshalIndent(v, "", " ")
1879 if !bytes.Equal(expect, got) {
1880 t.Fatalf("expect %q but got %q", string(expect), string(got))
1881 }
1882 }
1883
1884 func TestIssue104(t *testing.T) {
1885 type A struct {
1886 Field1 string
1887 Field2 int
1888 Field3 float64
1889 }
1890 type T struct {
1891 Field A
1892 }
1893 got, err := json.Marshal(T{})
1894 if err != nil {
1895 t.Fatal(err)
1896 }
1897 expect, _ := stdjson.Marshal(T{})
1898 if !bytes.Equal(expect, got) {
1899 t.Fatalf("expect %q but got %q", string(expect), string(got))
1900 }
1901 }
1902
1903 func TestIssue179(t *testing.T) {
1904 data := `
1905 {
1906 "t": {
1907 "t1": false,
1908 "t2": 0,
1909 "t3": "",
1910 "t4": [],
1911 "t5": null,
1912 "t6": null
1913 }
1914 }`
1915 type T struct {
1916 X struct {
1917 T1 bool `json:"t1,omitempty"`
1918 T2 float64 `json:"t2,omitempty"`
1919 T3 string `json:"t3,omitempty"`
1920 T4 []string `json:"t4,omitempty"`
1921 T5 *struct{} `json:"t5,omitempty"`
1922 T6 any `json:"t6,omitempty"`
1923 } `json:"x"`
1924 }
1925 var v T
1926 if err := stdjson.Unmarshal([]byte(data), &v); err != nil {
1927 t.Fatal(err)
1928 }
1929 var v2 T
1930 if err := json.Unmarshal([]byte(data), &v2); err != nil {
1931 t.Fatal(err)
1932 }
1933 if !reflect.DeepEqual(v, v2) {
1934 t.Fatalf("failed to decode: expected %v got %v", v, v2)
1935 }
1936 b1, err := stdjson.Marshal(v)
1937 if err != nil {
1938 t.Fatal(err)
1939 }
1940 b2, err := json.Marshal(v2)
1941 if err != nil {
1942 t.Fatal(err)
1943 }
1944 if !bytes.Equal(b1, b2) {
1945 t.Fatalf("failed to equal encoded result: expected %q but got %q", b1, b2)
1946 }
1947 }
1948
1949 func TestIssue180(t *testing.T) {
1950 v := struct {
1951 T struct {
1952 T1 bool `json:"t1"`
1953 T2 float64 `json:"t2"`
1954 T3 string `json:"t3"`
1955 T4 []string `json:"t4"`
1956 T5 *struct{} `json:"t5"`
1957 T6 any `json:"t6"`
1958 T7 [][]string `json:"t7"`
1959 } `json:"t"`
1960 }{
1961 T: struct {
1962 T1 bool `json:"t1"`
1963 T2 float64 `json:"t2"`
1964 T3 string `json:"t3"`
1965 T4 []string `json:"t4"`
1966 T5 *struct{} `json:"t5"`
1967 T6 any `json:"t6"`
1968 T7 [][]string `json:"t7"`
1969 }{
1970 T4: []string{},
1971 T7: [][]string{
1972 {""},
1973 {"hello", "world"},
1974 {},
1975 },
1976 },
1977 }
1978 b1, err := stdjson.MarshalIndent(v, "", "\t")
1979 if err != nil {
1980 t.Fatal(err)
1981 }
1982 b2, err := json.MarshalIndent(v, "", "\t")
1983 if err != nil {
1984 t.Fatal(err)
1985 }
1986 if !bytes.Equal(b1, b2) {
1987 t.Fatalf("failed to equal encoded result: expected %s but got %s", string(b1), string(b2))
1988 }
1989 }
1990
1991 func TestIssue235(t *testing.T) {
1992 type TaskMessage struct {
1993 Type string
1994 Payload map[string]any
1995 UniqueKey string
1996 }
1997 msg := TaskMessage{
1998 Payload: map[string]any{
1999 "sent_at": map[string]any{
2000 "Time": "0001-01-01T00:00:00Z",
2001 "Valid": false,
2002 },
2003 },
2004 }
2005 if _, err := json.Marshal(msg); err != nil {
2006 t.Fatal(err)
2007 }
2008 }
2009
2010 func TestEncodeMapKeyTypeInterface(t *testing.T) {
2011 // A map whose keys are of interface{} is refused, or encoded, as encoding/json of the Go it is built with
2012 // does ( see TestEncodeMapInterfaceKeys ).
2013 v := map[any]any{"a": 1}
2014 want, wantErr := stdjson.Marshal(v)
2015 got, err := json.Marshal(v)
2016 if (err == nil) != (wantErr == nil) {
2017 t.Fatalf("got the error %v, want %v", err, wantErr)
2018 }
2019 if err == nil && string(got) != string(want) {
2020 t.Fatalf("got %s, want %s", got, want)
2021 }
2022 }
2023
2024 type marshalContextKey struct{}
2025
2026 type marshalContextStructType struct{}
2027
2028 func (t *marshalContextStructType) MarshalJSON(ctx context.Context) ([]byte, error) {
2029 v := ctx.Value(marshalContextKey{})
2030 s, ok := v.(string)
2031 if !ok {
2032 return nil, fmt.Errorf("failed to propagate parent context.Context")
2033 }
2034 if s != "hello" {
2035 return nil, fmt.Errorf("failed to propagate parent context.Context")
2036 }
2037 return []byte(`"success"`), nil
2038 }
2039
2040 func TestEncodeContextOption(t *testing.T) {
2041 t.Run("MarshalContext", func(t *testing.T) {
2042 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello")
2043 b, err := json.MarshalContext(ctx, &marshalContextStructType{})
2044 if err != nil {
2045 t.Fatal(err)
2046 }
2047 if string(b) != `"success"` {
2048 t.Fatal("failed to encode with MarshalerContext")
2049 }
2050 })
2051 t.Run("EncodeContext", func(t *testing.T) {
2052 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello")
2053 buf := bytes.NewBuffer([]byte{})
2054 if err := json.NewEncoder(buf).EncodeContext(ctx, &marshalContextStructType{}); err != nil {
2055 t.Fatal(err)
2056 }
2057 if buf.String() != "\"success\"\n" {
2058 t.Fatal("failed to encode with EncodeContext")
2059 }
2060 })
2061 }
2062
2063 func TestInterfaceWithPointer(t *testing.T) {
2064 var (
2065 ivalue int = 10
2066 uvalue uint = 20
2067 svalue string = "value"
2068 bvalue bool = true
2069 fvalue float32 = 3.14
2070 nvalue json.Number = "1.23"
2071 structv = struct{ A int }{A: 10}
2072 slice = []int{1, 2, 3, 4}
2073 array = [4]int{1, 2, 3, 4}
2074 mapvalue = map[string]int{"a": 1}
2075 )
2076 data := map[string]any{
2077 "ivalue": ivalue,
2078 "uvalue": uvalue,
2079 "svalue": svalue,
2080 "bvalue": bvalue,
2081 "fvalue": fvalue,
2082 "nvalue": nvalue,
2083 "struct": structv,
2084 "slice": slice,
2085 "array": array,
2086 "map": mapvalue,
2087 "pivalue": &ivalue,
2088 "puvalue": &uvalue,
2089 "psvalue": &svalue,
2090 "pbvalue": &bvalue,
2091 "pfvalue": &fvalue,
2092 "pnvalue": &nvalue,
2093 "pstruct": &structv,
2094 "pslice": &slice,
2095 "parray": &array,
2096 "pmap": &mapvalue,
2097 }
2098 expected, err := stdjson.Marshal(data)
2099 if err != nil {
2100 t.Fatal(err)
2101 }
2102 actual, err := json.Marshal(data)
2103 if err != nil {
2104 t.Fatal(err)
2105 }
2106 assertEq(t, "any", string(expected), string(actual))
2107 }
2108
2109 func TestIssue263(t *testing.T) {
2110 type Foo struct {
2111 A []string `json:"a"`
2112 B int `json:"b"`
2113 }
2114
2115 type MyStruct struct {
2116 Foo *Foo `json:"foo,omitempty"`
2117 }
2118
2119 s := MyStruct{
2120 Foo: &Foo{
2121 A: []string{"ls -lah"},
2122 B: 0,
2123 },
2124 }
2125 expected, err := stdjson.Marshal(s)
2126 if err != nil {
2127 t.Fatal(err)
2128 }
2129 actual, err := json.Marshal(s)
2130 if err != nil {
2131 t.Fatal(err)
2132 }
2133 if !bytes.Equal(expected, actual) {
2134 t.Fatalf("expected:[%s] but got:[%s]", string(expected), string(actual))
2135 }
2136 }
2137
2138 func TestEmbeddedNotFirstField(t *testing.T) {
2139 type Embedded struct {
2140 Has bool `json:"has"`
2141 }
2142 type T struct {
2143 X int `json:"is"`
2144 Embedded `json:"child"`
2145 }
2146 p := T{X: 10, Embedded: Embedded{Has: true}}
2147 expected, err := stdjson.Marshal(&p)
2148 if err != nil {
2149 t.Fatal(err)
2150 }
2151 got, err := json.Marshal(&p)
2152 if err != nil {
2153 t.Fatal(err)
2154 }
2155 if !bytes.Equal(expected, got) {
2156 t.Fatalf("failed to encode embedded structure. expected = %q but got %q", expected, got)
2157 }
2158 }
2159
2160 type implementedMethodIface interface {
2161 M()
2162 }
2163
2164 type implementedIfaceType struct {
2165 A int
2166 B string
2167 }
2168
2169 func (implementedIfaceType) M() {}
2170
2171 func TestImplementedMethodInterfaceType(t *testing.T) {
2172 data := []implementedIfaceType{{}}
2173 expected, err := stdjson.Marshal(data)
2174 if err != nil {
2175 t.Fatal(err)
2176 }
2177 got, err := json.Marshal(data)
2178 if err != nil {
2179 t.Fatal(err)
2180 }
2181 if !bytes.Equal(expected, got) {
2182 t.Fatalf("failed to encode implemented method interface type. expected:[%q] but got:[%q]", expected, got)
2183 }
2184 }
2185
2186 func TestEmptyStructInterface(t *testing.T) {
2187 expected, err := stdjson.Marshal([]any{struct{}{}})
2188 if err != nil {
2189 t.Fatal(err)
2190 }
2191 got, err := json.Marshal([]any{struct{}{}})
2192 if err != nil {
2193 t.Fatal(err)
2194 }
2195 if !bytes.Equal(expected, got) {
2196 t.Fatalf("failed to encode empty struct interface. expected:[%q] but got:[%q]", expected, got)
2197 }
2198 }
2199
2200 func TestIssue290(t *testing.T) {
2201 type Issue290 interface {
2202 A()
2203 }
2204 var a struct {
2205 A Issue290
2206 }
2207 expected, err := stdjson.Marshal(a)
2208 if err != nil {
2209 t.Fatal(err)
2210 }
2211 got, err := json.Marshal(a)
2212 if err != nil {
2213 t.Fatal(err)
2214 }
2215 if !bytes.Equal(expected, got) {
2216 t.Fatalf("failed to encode non empty interface. expected = %q but got %q", expected, got)
2217 }
2218 }
2219
2220 func TestIssue299(t *testing.T) {
2221 t.Run("conflict second field", func(t *testing.T) {
2222 type Embedded struct {
2223 ID string `json:"id"`
2224 Name map[string]string `json:"name"`
2225 }
2226 type Container struct {
2227 Embedded
2228 Name string `json:"name"`
2229 }
2230 c := &Container{
2231 Embedded: Embedded{
2232 ID: "1",
2233 Name: map[string]string{"en": "Hello", "es": "Hola"},
2234 },
2235 Name: "Hi",
2236 }
2237 expected, _ := stdjson.Marshal(c)
2238 got, err := json.Marshal(c)
2239 if err != nil {
2240 t.Fatal(err)
2241 }
2242 if !bytes.Equal(expected, got) {
2243 t.Fatalf("expected %q but got %q", expected, got)
2244 }
2245 })
2246 t.Run("conflict map field", func(t *testing.T) {
2247 type Embedded struct {
2248 Name map[string]string `json:"name"`
2249 }
2250 type Container struct {
2251 Embedded
2252 Name string `json:"name"`
2253 }
2254 c := &Container{
2255 Embedded: Embedded{
2256 Name: map[string]string{"en": "Hello", "es": "Hola"},
2257 },
2258 Name: "Hi",
2259 }
2260 expected, _ := stdjson.Marshal(c)
2261 got, err := json.Marshal(c)
2262 if err != nil {
2263 t.Fatal(err)
2264 }
2265 if !bytes.Equal(expected, got) {
2266 t.Fatalf("expected %q but got %q", expected, got)
2267 }
2268 })
2269 t.Run("conflict slice field", func(t *testing.T) {
2270 type Embedded struct {
2271 Name []string `json:"name"`
2272 }
2273 type Container struct {
2274 Embedded
2275 Name string `json:"name"`
2276 }
2277 c := &Container{
2278 Embedded: Embedded{
2279 Name: []string{"Hello"},
2280 },
2281 Name: "Hi",
2282 }
2283 expected, _ := stdjson.Marshal(c)
2284 got, err := json.Marshal(c)
2285 if err != nil {
2286 t.Fatal(err)
2287 }
2288 if !bytes.Equal(expected, got) {
2289 t.Fatalf("expected %q but got %q", expected, got)
2290 }
2291 })
2292 }
2293
2294 func TestRecursivePtrHead(t *testing.T) {
2295 type User struct {
2296 Account *string `json:"account"`
2297 Password *string `json:"password"`
2298 Nickname *string `json:"nickname"`
2299 Address *string `json:"address,omitempty"`
2300 Friends []*User `json:"friends,omitempty"`
2301 }
2302 user1Account, user1Password, user1Nickname := "abcdef", "123456", "user1"
2303 user1 := &User{
2304 Account: &user1Account,
2305 Password: &user1Password,
2306 Nickname: &user1Nickname,
2307 Address: nil,
2308 }
2309 user2Account, user2Password, user2Nickname := "ghijkl", "123456", "user2"
2310 user2 := &User{
2311 Account: &user2Account,
2312 Password: &user2Password,
2313 Nickname: &user2Nickname,
2314 Address: nil,
2315 }
2316 user1.Friends = []*User{user2}
2317 expected, err := stdjson.Marshal(user1)
2318 if err != nil {
2319 t.Fatal(err)
2320 }
2321 got, err := json.Marshal(user1)
2322 if err != nil {
2323 t.Fatal(err)
2324 }
2325 if !bytes.Equal(expected, got) {
2326 t.Fatalf("failed to encode. expected %q but got %q", expected, got)
2327 }
2328 }
2329
2330 func TestMarshalIndent(t *testing.T) {
2331 v := map[string]map[string]any{
2332 "a": {
2333 "b": "1",
2334 "c": map[string]any{
2335 "d": "1",
2336 },
2337 },
2338 }
2339 expected, err := stdjson.MarshalIndent(v, "", " ")
2340 if err != nil {
2341 t.Fatal(err)
2342 }
2343 got, err := json.MarshalIndent(v, "", " ")
2344 if err != nil {
2345 t.Fatal(err)
2346 }
2347 if !bytes.Equal(expected, got) {
2348 t.Fatalf("expected: %q but got %q", expected, got)
2349 }
2350 }
2351
2352 type issue318Embedded struct {
2353 _ [64]byte
2354 }
2355
2356 type issue318 struct {
2357 issue318Embedded `json:"-"`
2358 ID issue318MarshalText `json:"id,omitempty"`
2359 }
2360
2361 type issue318MarshalText struct {
2362 ID string
2363 }
2364
2365 func (i issue318MarshalText) MarshalText() ([]byte, error) {
2366 return []byte(i.ID), nil
2367 }
2368
2369 func TestIssue318(t *testing.T) {
2370 v := issue318{
2371 ID: issue318MarshalText{ID: "1"},
2372 }
2373 b, err := json.Marshal(v)
2374 if err != nil {
2375 t.Fatal(err)
2376 }
2377 expected := `{"id":"1"}`
2378 if string(b) != expected {
2379 t.Fatalf("failed to encode. expected %s but got %s", expected, string(b))
2380 }
2381 }
2382
2383 type emptyStringMarshaler struct {
2384 Value stringMarshaler `json:"value,omitempty"`
2385 }
2386
2387 type stringMarshaler string
2388
2389 func (s stringMarshaler) MarshalJSON() ([]byte, error) {
2390 return []byte(`"` + s + `"`), nil
2391 }
2392
2393 func TestEmptyStringMarshaler(t *testing.T) {
2394 value := emptyStringMarshaler{}
2395 expected, err := stdjson.Marshal(value)
2396 assertErr(t, err)
2397 got, err := json.Marshal(value)
2398 assertErr(t, err)
2399 assertEq(t, "struct", string(expected), string(got))
2400 }
2401
2402 func TestIssue324(t *testing.T) {
2403 type T struct {
2404 FieldA *string `json:"fieldA,omitempty"`
2405 FieldB *string `json:"fieldB,omitempty"`
2406 FieldC *bool `json:"fieldC"`
2407 FieldD []string `json:"fieldD,omitempty"`
2408 }
2409 v := &struct {
2410 Code string `json:"code"`
2411 *T
2412 }{
2413 T: &T{},
2414 }
2415 var sv = "Test Field"
2416 v.Code = "Test"
2417 v.T.FieldB = &sv
2418 expected, err := stdjson.Marshal(v)
2419 if err != nil {
2420 t.Fatal(err)
2421 }
2422 got, err := json.Marshal(v)
2423 if err != nil {
2424 t.Fatal(err)
2425 }
2426 if !bytes.Equal(expected, got) {
2427 t.Fatalf("failed to encode. expected %q but got %q", expected, got)
2428 }
2429 }
2430
2431 func TestIssue339(t *testing.T) {
2432 type T1 struct {
2433 *big.Int
2434 }
2435 type T2 struct {
2436 T1 T1 `json:"T1"`
2437 }
2438 v := T2{T1{Int: big.NewInt(10000)}}
2439 b, err := json.Marshal(&v)
2440 assertErr(t, err)
2441 got := string(b)
2442 expected := `{"T1":10000}`
2443 if got != expected {
2444 t.Errorf("unexpected result: %v != %v", got, expected)
2445 }
2446 }
2447
2448 func TestIssue376(t *testing.T) {
2449 type Container struct {
2450 V any `json:"value"`
2451 }
2452 type MapOnly struct {
2453 Map map[string]int64 `json:"map"`
2454 }
2455 b, err := json.Marshal(Container{MapOnly{}})
2456 if err != nil {
2457 t.Fatal(err)
2458 }
2459 got := string(b)
2460 expected := `{"value":{"map":null}}`
2461 if got != expected {
2462 t.Errorf("unexpected result: %v != %v", got, expected)
2463 }
2464 }
2465
2466 type Issue370 struct {
2467 String string
2468 Valid bool
2469 }
2470
2471 func (i *Issue370) MarshalJSON() ([]byte, error) {
2472 if !i.Valid {
2473 return json.Marshal(nil)
2474 }
2475 return json.Marshal(i.String)
2476 }
2477
2478 func TestIssue370(t *testing.T) {
2479 v := []struct {
2480 V Issue370
2481 }{
2482 {V: Issue370{String: "test", Valid: true}},
2483 }
2484 b, err := json.Marshal(v)
2485 if err != nil {
2486 t.Fatal(err)
2487 }
2488 got := string(b)
2489 expected := `[{"V":"test"}]`
2490 if got != expected {
2491 t.Errorf("unexpected result: %v != %v", got, expected)
2492 }
2493 }
2494
2495 func TestIssue374(t *testing.T) {
2496 r := io.MultiReader(strings.NewReader(strings.Repeat(" ", 505)+`"\u`), strings.NewReader(`0000"`))
2497 var v any
2498 if err := json.NewDecoder(r).Decode(&v); err != nil {
2499 t.Fatal(err)
2500 }
2501 got := v.(string)
2502 expected := "\u0000"
2503 if got != expected {
2504 t.Errorf("unexpected result: %q != %q", got, expected)
2505 }
2506 }
2507
2508 func TestIssue381(t *testing.T) {
2509 var v struct {
2510 Field0 bool
2511 Field1 bool
2512 Field2 bool
2513 Field3 bool
2514 Field4 bool
2515 Field5 bool
2516 Field6 bool
2517 Field7 bool
2518 Field8 bool
2519 Field9 bool
2520 Field10 bool
2521 Field11 bool
2522 Field12 bool
2523 Field13 bool
2524 Field14 bool
2525 Field15 bool
2526 Field16 bool
2527 Field17 bool
2528 Field18 bool
2529 Field19 bool
2530 Field20 bool
2531 Field21 bool
2532 Field22 bool
2533 Field23 bool
2534 Field24 bool
2535 Field25 bool
2536 Field26 bool
2537 Field27 bool
2538 Field28 bool
2539 Field29 bool
2540 Field30 bool
2541 Field31 bool
2542 Field32 bool
2543 Field33 bool
2544 Field34 bool
2545 Field35 bool
2546 Field36 bool
2547 Field37 bool
2548 Field38 bool
2549 Field39 bool
2550 Field40 bool
2551 Field41 bool
2552 Field42 bool
2553 Field43 bool
2554 Field44 bool
2555 Field45 bool
2556 Field46 bool
2557 Field47 bool
2558 Field48 bool
2559 Field49 bool
2560 Field50 bool
2561 Field51 bool
2562 Field52 bool
2563 Field53 bool
2564 Field54 bool
2565 Field55 bool
2566 Field56 bool
2567 Field57 bool
2568 Field58 bool
2569 Field59 bool
2570 Field60 bool
2571 Field61 bool
2572 Field62 bool
2573 Field63 bool
2574 Field64 bool
2575 Field65 bool
2576 Field66 bool
2577 Field67 bool
2578 Field68 bool
2579 Field69 bool
2580 Field70 bool
2581 Field71 bool
2582 Field72 bool
2583 Field73 bool
2584 Field74 bool
2585 Field75 bool
2586 Field76 bool
2587 Field77 bool
2588 Field78 bool
2589 Field79 bool
2590 Field80 bool
2591 Field81 bool
2592 Field82 bool
2593 Field83 bool
2594 Field84 bool
2595 Field85 bool
2596 Field86 bool
2597 Field87 bool
2598 Field88 bool
2599 Field89 bool
2600 Field90 bool
2601 Field91 bool
2602 Field92 bool
2603 Field93 bool
2604 Field94 bool
2605 Field95 bool
2606 Field96 bool
2607 Field97 bool
2608 Field98 bool
2609 Field99 bool
2610 }
2611
2612 // test encoder cache issue, not related to encoder
2613 b, err := json.Marshal(v)
2614 if err != nil {
2615 t.Errorf("failed to marshal %s", err.Error())
2616 t.FailNow()
2617 }
2618
2619 std, err := stdjson.Marshal(v)
2620 if err != nil {
2621 t.Errorf("failed to marshal with encoding/json %s", err.Error())
2622 t.FailNow()
2623 }
2624
2625 if !bytes.Equal(std, b) {
2626 t.Errorf("encoding result not equal to encoding/json")
2627 t.FailNow()
2628 }
2629 }
2630
2631 func TestIssue386(t *testing.T) {
2632 raw := `{"date": null, "platform": "\u6f2b\u753b", "images": {"small": "https://lain.bgm.tv/pic/cover/s/d2/a1/80048_jp.jpg", "grid": "https://lain.bgm.tv/pic/cover/g/d2/a1/80048_jp.jpg", "large": "https://lain.bgm.tv/pic/cover/l/d2/a1/80048_jp.jpg", "medium": "https://lain.bgm.tv/pic/cover/m/d2/a1/80048_jp.jpg", "common": "https://lain.bgm.tv/pic/cover/c/d2/a1/80048_jp.jpg"}, "summary": "\u5929\u624d\u8a2d\u8a08\u58eb\u30fb\u5929\u5bae\uff08\u3042\u307e\u307f\u3084\uff09\u3092\u62b1\u3048\u308b\u6751\u96e8\u7dcf\u5408\u4f01\u753b\u306f\u3001\u771f\u6c34\u5efa\u8a2d\u3068\u63d0\u643a\u3057\u3066\u300c\u3055\u304d\u305f\u307e\u30a2\u30ea\u30fc\u30ca\u300d\u306e\u30b3\u30f3\u30da\u306b\u512a\u52dd\u3059\u308b\u3053\u3068\u306b\u8ced\u3051\u3066\u3044\u305f\u3002\u3057\u304b\u3057\u3001\u73fe\u77e5\u4e8b\u306e\u6d25\u5730\u7530\uff08\u3064\u3061\u3060\uff09\u306f\u5927\u65e5\u5efa\u8a2d\u306b\u512a\u52dd\u3055\u305b\u3088\u3046\u3068\u6697\u8e8d\u3059\u308b\u3002\u305d\u308c\u306f\u73fe\u77e5\u4e8b\u306e\u6d25\u5730\u7530\u3068\u526f\u77e5\u4e8b\u306e\u592a\u7530\uff08\u304a\u304a\u305f\uff09\u306e\u653f\u6cbb\u751f\u547d\u3092\u5de6\u53f3\u3059\u308b\u4e89\u3044\u3068\u306a\u308a\u2026\u2026!?\u3000\u305d\u3057\u3066\u516c\u5171\u4e8b\u696d\u306b\u6e26\u5dfb\u304f\u6df1\u3044\u95c7\u306b\u842c\u7530\u9280\u6b21\u90ce\uff08\u307e\u3093\u3060\u30fb\u304e\u3093\u3058\u308d\u3046\uff09\u306f\u2026\u2026!?", "name": "\u30df\u30ca\u30df\u306e\u5e1d\u738b (48)"}`
2633 var a struct {
2634 Date *string `json:"date"`
2635 Platform *string `json:"platform"`
2636 Summary string `json:"summary"`
2637 Name string `json:"name"`
2638 }
2639 err := json.NewDecoder(strings.NewReader(raw)).Decode(&a)
2640 if err != nil {
2641 t.Error(err)
2642 }
2643 }
2644
2645 type customMapKey string
2646
2647 func (b customMapKey) MarshalJSON() ([]byte, error) {
2648 return []byte("[]"), nil
2649 }
2650
2651 func TestCustomMarshalForMapKey(t *testing.T) {
2652 m := map[customMapKey]string{customMapKey("skipcustom"): "test"}
2653 expected, err := stdjson.Marshal(m)
2654 assertErr(t, err)
2655 got, err := json.Marshal(m)
2656 assertErr(t, err)
2657 assertEq(t, "custom map key", string(expected), string(got))
2658 }
2659
2660 func TestIssue391(t *testing.T) {
2661 type A struct {
2662 X string `json:"x,omitempty"`
2663 }
2664 type B struct {
2665 A
2666 }
2667 type C struct {
2668 X []int `json:"x,omitempty"`
2669 }
2670 for _, tc := range []struct {
2671 name string
2672 in any
2673 out string
2674 }{
2675 {in: struct{ B }{}, out: "{}"},
2676 {in: struct {
2677 B
2678 Y string `json:"y"`
2679 }{}, out: `{"y":""}`},
2680 {in: struct {
2681 Y string `json:"y"`
2682 B
2683 }{}, out: `{"y":""}`},
2684 {in: struct{ C }{}, out: "{}"},
2685 } {
2686 t.Run(tc.name, func(t *testing.T) {
2687 b, err := json.Marshal(tc.in)
2688 assertErr(t, err)
2689 assertEq(t, "unexpected result", tc.out, string(b))
2690 })
2691 }
2692 }
2693
2694 func TestIssue417(t *testing.T) {
2695 x := map[string]string{
2696 "b": "b",
2697 "a": "a",
2698 }
2699 b, err := json.MarshalIndentWithOption(x, "", " ", json.UnorderedMap())
2700 assertErr(t, err)
2701
2702 var y map[string]string
2703 err = json.Unmarshal(b, &y)
2704 assertErr(t, err)
2705
2706 assertEq(t, "key b", "b", y["b"])
2707 assertEq(t, "key a", "a", y["a"])
2708 }
2709
2710 func TestIssue426(t *testing.T) {
2711 type I interface {
2712 Foo()
2713 }
2714 type A struct {
2715 I
2716 Val string
2717 }
2718 var s A
2719 s.Val = "456"
2720
2721 b, _ := json.Marshal(s)
2722 assertEq(t, "unexpected result", `{"I":null,"Val":"456"}`, string(b))
2723 }
2724
2725 func TestIssue441(t *testing.T) {
2726 type A struct {
2727 Y string `json:"y,omitempty"`
2728 }
2729
2730 type B struct {
2731 X *int `json:"x,omitempty"`
2732 A
2733 Z int `json:"z,omitempty"`
2734 }
2735
2736 b, err := json.Marshal(B{})
2737 assertErr(t, err)
2738 assertEq(t, "unexpected result", "{}", string(b))
2739 }
2740
2741 func TestIssue459(t *testing.T) {
2742 type A struct {
2743 A *A `json:"a,omitempty"`
2744 }
2745
2746 type B struct {
2747 A
2748 }
2749
2750 b, err := json.Marshal(B{})
2751 assertErr(t, err)
2752 assertEq(t, "unexpected result", "{}", string(b))
2753 }
2754
2755 // The data word of an interface value is nil both for a nil pointer and for a struct of a single pointer
2756 // whose pointer is nil. The former is null, and the latter is a value.
2757 func TestEncodeInterfaceValueWithNilDataWord(t *testing.T) {
2758 type directStruct struct {
2759 P *int
2760 }
2761 type directMapStruct struct {
2762 M map[string]int
2763 }
2764 type nonEmptyInterface interface {
2765 M()
2766 }
2767 for _, test := range []struct {
2768 name string
2769 v any
2770 expected string
2771 }{
2772 {"nil", nil, `[null]`},
2773 {"nil pointer", (*int)(nil), `[null]`},
2774 {"nil pointer to struct", (*directStruct)(nil), `[null]`},
2775 {"nil pointer to unsupported type", (*chan int)(nil), `[null]`},
2776 {"nil map", map[string]int(nil), `[null]`},
2777 {"struct of nil pointer", directStruct{}, `[{"P":null}]`},
2778 {"struct of nil map", directMapStruct{}, `[{"M":null}]`},
2779 } {
2780 t.Run(test.name, func(t *testing.T) {
2781 for i := 0; i < 2; i++ {
2782 got, err := json.Marshal([]any{test.v})
2783 if err != nil {
2784 t.Fatal(err)
2785 }
2786 if string(got) != test.expected {
2787 t.Fatalf("call %d: expected %s but got %s", i, test.expected, got)
2788 }
2789 }
2790 })
2791 }
2792 t.Run("non-empty interface of nil pointer", func(t *testing.T) {
2793 got, err := json.Marshal(struct{ V nonEmptyInterface }{})
2794 if err != nil {
2795 t.Fatal(err)
2796 }
2797 if expected := `{"V":null}`; string(got) != expected {
2798 t.Fatalf("expected %s but got %s", expected, got)
2799 }
2800 })
2801 }