github.com/3JoB/go-json@v0.10.4/encode_test.go (about) 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 "regexp" 15 "strconv" 16 "strings" 17 "testing" 18 "time" 19 20 "github.com/3JoB/go-reflect" 21 22 "github.com/3JoB/go-json" 23 ) 24 25 type recursiveT struct { 26 A *recursiveT `json:"a,omitempty"` 27 B *recursiveU `json:"b,omitempty"` 28 C *recursiveU `json:"c,omitempty"` 29 D string `json:"d,omitempty"` 30 } 31 32 type recursiveU struct { 33 T *recursiveT `json:"t,omitempty"` 34 } 35 36 func Test_Marshal(t *testing.T) { 37 t.Run("int", func(t *testing.T) { 38 bytes, err := json.Marshal(-10) 39 assertErr(t, err) 40 assertEq(t, "int", `-10`, string(bytes)) 41 }) 42 t.Run("int8", func(t *testing.T) { 43 bytes, err := json.Marshal(int8(-11)) 44 assertErr(t, err) 45 assertEq(t, "int8", `-11`, string(bytes)) 46 }) 47 t.Run("int16", func(t *testing.T) { 48 bytes, err := json.Marshal(int16(-12)) 49 assertErr(t, err) 50 assertEq(t, "int16", `-12`, string(bytes)) 51 }) 52 t.Run("int32", func(t *testing.T) { 53 bytes, err := json.Marshal(int32(-13)) 54 assertErr(t, err) 55 assertEq(t, "int32", `-13`, string(bytes)) 56 }) 57 t.Run("int64", func(t *testing.T) { 58 bytes, err := json.Marshal(int64(-14)) 59 assertErr(t, err) 60 assertEq(t, "int64", `-14`, string(bytes)) 61 }) 62 t.Run("uint", func(t *testing.T) { 63 bytes, err := json.Marshal(uint(10)) 64 assertErr(t, err) 65 assertEq(t, "uint", `10`, string(bytes)) 66 }) 67 t.Run("uint8", func(t *testing.T) { 68 bytes, err := json.Marshal(uint8(11)) 69 assertErr(t, err) 70 assertEq(t, "uint8", `11`, string(bytes)) 71 }) 72 t.Run("uint16", func(t *testing.T) { 73 bytes, err := json.Marshal(uint16(12)) 74 assertErr(t, err) 75 assertEq(t, "uint16", `12`, string(bytes)) 76 }) 77 t.Run("uint32", func(t *testing.T) { 78 bytes, err := json.Marshal(uint32(13)) 79 assertErr(t, err) 80 assertEq(t, "uint32", `13`, string(bytes)) 81 }) 82 t.Run("uint64", func(t *testing.T) { 83 bytes, err := json.Marshal(uint64(14)) 84 assertErr(t, err) 85 assertEq(t, "uint64", `14`, string(bytes)) 86 }) 87 t.Run("float32", func(t *testing.T) { 88 bytes, err := json.Marshal(float32(3.14)) 89 assertErr(t, err) 90 assertEq(t, "float32", `3.14`, string(bytes)) 91 }) 92 t.Run("float64", func(t *testing.T) { 93 bytes, err := json.Marshal(float64(3.14)) 94 assertErr(t, err) 95 assertEq(t, "float64", `3.14`, string(bytes)) 96 }) 97 t.Run("bool", func(t *testing.T) { 98 bytes, err := json.Marshal(true) 99 assertErr(t, err) 100 assertEq(t, "bool", `true`, string(bytes)) 101 }) 102 t.Run("string", func(t *testing.T) { 103 bytes, err := json.Marshal("hello world") 104 assertErr(t, err) 105 assertEq(t, "string", `"hello world"`, string(bytes)) 106 }) 107 t.Run("struct", func(t *testing.T) { 108 bytes, err := json.Marshal(struct { 109 A int `json:"a"` 110 B uint `json:"b"` 111 C string `json:"c"` 112 D int `json:"-"` // ignore field 113 a int `json:"aa"` // private field 114 }{ 115 A: -1, 116 B: 1, 117 C: "hello world", 118 }) 119 assertErr(t, err) 120 assertEq(t, "struct", `{"a":-1,"b":1,"c":"hello world"}`, string(bytes)) 121 t.Run("null", func(t *testing.T) { 122 type T struct { 123 A *struct{} `json:"a"` 124 } 125 var v T 126 bytes, err := json.Marshal(&v) 127 assertErr(t, err) 128 assertEq(t, "struct", `{"a":null}`, string(bytes)) 129 }) 130 t.Run("recursive", func(t *testing.T) { 131 bytes, err := json.Marshal(recursiveT{ 132 A: &recursiveT{ 133 B: &recursiveU{ 134 T: &recursiveT{ 135 D: "hello", 136 }, 137 }, 138 C: &recursiveU{ 139 T: &recursiveT{ 140 D: "world", 141 }, 142 }, 143 }, 144 }) 145 assertErr(t, err) 146 assertEq(t, "recursive", `{"a":{"b":{"t":{"d":"hello"}},"c":{"t":{"d":"world"}}}}`, string(bytes)) 147 }) 148 t.Run("embedded", func(t *testing.T) { 149 type T struct { 150 A string `json:"a"` 151 } 152 type U struct { 153 *T 154 B string `json:"b"` 155 } 156 type T2 struct { 157 A string `json:"a,omitempty"` 158 } 159 type U2 struct { 160 *T2 161 B string `json:"b,omitempty"` 162 } 163 t.Run("exists field", func(t *testing.T) { 164 bytes, err := json.Marshal(&U{ 165 T: &T{ 166 A: "aaa", 167 }, 168 B: "bbb", 169 }) 170 assertErr(t, err) 171 assertEq(t, "embedded", `{"a":"aaa","b":"bbb"}`, string(bytes)) 172 t.Run("omitempty", func(t *testing.T) { 173 bytes, err := json.Marshal(&U2{ 174 T2: &T2{ 175 A: "aaa", 176 }, 177 B: "bbb", 178 }) 179 assertErr(t, err) 180 assertEq(t, "embedded", `{"a":"aaa","b":"bbb"}`, string(bytes)) 181 }) 182 }) 183 t.Run("none field", func(t *testing.T) { 184 bytes, err := json.Marshal(&U{ 185 B: "bbb", 186 }) 187 assertErr(t, err) 188 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes)) 189 t.Run("omitempty", func(t *testing.T) { 190 bytes, err := json.Marshal(&U2{ 191 B: "bbb", 192 }) 193 assertErr(t, err) 194 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes)) 195 }) 196 }) 197 }) 198 199 t.Run("embedded with tag", func(t *testing.T) { 200 type T struct { 201 A string `json:"a"` 202 } 203 type U struct { 204 *T `json:"t"` 205 B string `json:"b"` 206 } 207 type T2 struct { 208 A string `json:"a,omitempty"` 209 } 210 type U2 struct { 211 *T2 `json:"t,omitempty"` 212 B string `json:"b,omitempty"` 213 } 214 t.Run("exists field", func(t *testing.T) { 215 bytes, err := json.Marshal(&U{ 216 T: &T{ 217 A: "aaa", 218 }, 219 B: "bbb", 220 }) 221 assertErr(t, err) 222 assertEq(t, "embedded", `{"t":{"a":"aaa"},"b":"bbb"}`, string(bytes)) 223 t.Run("omitempty", func(t *testing.T) { 224 bytes, err := json.Marshal(&U2{ 225 T2: &T2{ 226 A: "aaa", 227 }, 228 B: "bbb", 229 }) 230 assertErr(t, err) 231 assertEq(t, "embedded", `{"t":{"a":"aaa"},"b":"bbb"}`, string(bytes)) 232 }) 233 }) 234 235 t.Run("none field", func(t *testing.T) { 236 bytes, err := json.Marshal(&U{ 237 B: "bbb", 238 }) 239 assertErr(t, err) 240 assertEq(t, "embedded", `{"t":null,"b":"bbb"}`, string(bytes)) 241 t.Run("omitempty", func(t *testing.T) { 242 bytes, err := json.Marshal(&U2{ 243 B: "bbb", 244 }) 245 assertErr(t, err) 246 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes)) 247 }) 248 }) 249 }) 250 251 t.Run("omitempty", func(t *testing.T) { 252 type T struct { 253 A int `json:",omitempty"` 254 B int8 `json:",omitempty"` 255 C int16 `json:",omitempty"` 256 D int32 `json:",omitempty"` 257 E int64 `json:",omitempty"` 258 F uint `json:",omitempty"` 259 G uint8 `json:",omitempty"` 260 H uint16 `json:",omitempty"` 261 I uint32 `json:",omitempty"` 262 J uint64 `json:",omitempty"` 263 K float32 `json:",omitempty"` 264 L float64 `json:",omitempty"` 265 O string `json:",omitempty"` 266 P bool `json:",omitempty"` 267 Q []int `json:",omitempty"` 268 R map[string]any `json:",omitempty"` 269 S *struct{} `json:",omitempty"` 270 T int `json:"t,omitempty"` 271 } 272 var v T 273 v.T = 1 274 bytes, err := json.Marshal(&v) 275 assertErr(t, err) 276 assertEq(t, "struct", `{"t":1}`, string(bytes)) 277 t.Run("int", func(t *testing.T) { 278 var v struct { 279 A int `json:"a,omitempty"` 280 B int `json:"b"` 281 } 282 v.B = 1 283 bytes, err := json.Marshal(&v) 284 assertErr(t, err) 285 assertEq(t, "int", `{"b":1}`, string(bytes)) 286 }) 287 t.Run("int8", func(t *testing.T) { 288 var v struct { 289 A int `json:"a,omitempty"` 290 B int8 `json:"b"` 291 } 292 v.B = 1 293 bytes, err := json.Marshal(&v) 294 assertErr(t, err) 295 assertEq(t, "int8", `{"b":1}`, string(bytes)) 296 }) 297 t.Run("int16", func(t *testing.T) { 298 var v struct { 299 A int `json:"a,omitempty"` 300 B int16 `json:"b"` 301 } 302 v.B = 1 303 bytes, err := json.Marshal(&v) 304 assertErr(t, err) 305 assertEq(t, "int16", `{"b":1}`, string(bytes)) 306 }) 307 t.Run("int32", func(t *testing.T) { 308 var v struct { 309 A int `json:"a,omitempty"` 310 B int32 `json:"b"` 311 } 312 v.B = 1 313 bytes, err := json.Marshal(&v) 314 assertErr(t, err) 315 assertEq(t, "int32", `{"b":1}`, string(bytes)) 316 }) 317 t.Run("int64", func(t *testing.T) { 318 var v struct { 319 A int `json:"a,omitempty"` 320 B int64 `json:"b"` 321 } 322 v.B = 1 323 bytes, err := json.Marshal(&v) 324 assertErr(t, err) 325 assertEq(t, "int64", `{"b":1}`, string(bytes)) 326 }) 327 t.Run("string", func(t *testing.T) { 328 var v struct { 329 A int `json:"a,omitempty"` 330 B string `json:"b"` 331 } 332 v.B = "b" 333 bytes, err := json.Marshal(&v) 334 assertErr(t, err) 335 assertEq(t, "string", `{"b":"b"}`, string(bytes)) 336 }) 337 t.Run("float32", func(t *testing.T) { 338 var v struct { 339 A int `json:"a,omitempty"` 340 B float32 `json:"b"` 341 } 342 v.B = 1.1 343 bytes, err := json.Marshal(&v) 344 assertErr(t, err) 345 assertEq(t, "float32", `{"b":1.1}`, string(bytes)) 346 }) 347 t.Run("float64", func(t *testing.T) { 348 var v struct { 349 A int `json:"a,omitempty"` 350 B float64 `json:"b"` 351 } 352 v.B = 3.14 353 bytes, err := json.Marshal(&v) 354 assertErr(t, err) 355 assertEq(t, "float64", `{"b":3.14}`, string(bytes)) 356 }) 357 t.Run("slice", func(t *testing.T) { 358 var v struct { 359 A int `json:"a,omitempty"` 360 B []int `json:"b"` 361 } 362 v.B = []int{1, 2, 3} 363 bytes, err := json.Marshal(&v) 364 assertErr(t, err) 365 assertEq(t, "slice", `{"b":[1,2,3]}`, string(bytes)) 366 }) 367 t.Run("array", func(t *testing.T) { 368 var v struct { 369 A int `json:"a,omitempty"` 370 B [2]int `json:"b"` 371 } 372 v.B = [2]int{1, 2} 373 bytes, err := json.Marshal(&v) 374 assertErr(t, err) 375 assertEq(t, "array", `{"b":[1,2]}`, string(bytes)) 376 }) 377 t.Run("map", func(t *testing.T) { 378 v := new(struct { 379 A int `json:"a,omitempty"` 380 B map[string]any `json:"b"` 381 }) 382 v.B = map[string]any{"c": 1} 383 bytes, err := json.Marshal(v) 384 assertErr(t, err) 385 assertEq(t, "array", `{"b":{"c":1}}`, string(bytes)) 386 }) 387 }) 388 t.Run("head_omitempty", func(t *testing.T) { 389 type T struct { 390 A *struct{} `json:"a,omitempty"` 391 } 392 var v T 393 bytes, err := json.Marshal(&v) 394 assertErr(t, err) 395 assertEq(t, "struct", `{}`, string(bytes)) 396 }) 397 t.Run("pointer_head_omitempty", func(t *testing.T) { 398 type V struct{} 399 type U struct { 400 B *V `json:"b,omitempty"` 401 } 402 type T struct { 403 A *U `json:"a"` 404 } 405 bytes, err := json.Marshal(&T{A: &U{}}) 406 assertErr(t, err) 407 assertEq(t, "struct", `{"a":{}}`, string(bytes)) 408 }) 409 t.Run("head_int_omitempty", func(t *testing.T) { 410 type T struct { 411 A int `json:"a,omitempty"` 412 } 413 var v T 414 bytes, err := json.Marshal(&v) 415 assertErr(t, err) 416 assertEq(t, "struct", `{}`, string(bytes)) 417 }) 418 }) 419 t.Run("slice", func(t *testing.T) { 420 t.Run("[]int", func(t *testing.T) { 421 bytes, err := json.Marshal([]int{1, 2, 3, 4}) 422 assertErr(t, err) 423 assertEq(t, "[]int", `[1,2,3,4]`, string(bytes)) 424 }) 425 t.Run("[]interface{}", func(t *testing.T) { 426 bytes, err := json.Marshal([]any{1, 2.1, "hello"}) 427 assertErr(t, err) 428 assertEq(t, "[]interface{}", `[1,2.1,"hello"]`, string(bytes)) 429 }) 430 }) 431 432 t.Run("array", func(t *testing.T) { 433 bytes, err := json.Marshal([4]int{1, 2, 3, 4}) 434 assertErr(t, err) 435 assertEq(t, "array", `[1,2,3,4]`, string(bytes)) 436 }) 437 t.Run("map", func(t *testing.T) { 438 t.Run("map[string]int", func(t *testing.T) { 439 v := map[string]int{ 440 "a": 1, 441 "b": 2, 442 "c": 3, 443 "d": 4, 444 } 445 bytes, err := json.Marshal(v) 446 assertErr(t, err) 447 assertEq(t, "map", `{"a":1,"b":2,"c":3,"d":4}`, string(bytes)) 448 b, err := json.MarshalWithOption(v, json.UnorderedMap()) 449 assertErr(t, err) 450 assertEq(t, "unordered map", len(`{"a":1,"b":2,"c":3,"d":4}`), len(string(b))) 451 }) 452 t.Run("map[string]interface{}", func(t *testing.T) { 453 type T struct { 454 A int 455 } 456 v := map[string]any{ 457 "a": 1, 458 "b": 2.1, 459 "c": &T{ 460 A: 10, 461 }, 462 "d": 4, 463 } 464 bytes, err := json.Marshal(v) 465 assertErr(t, err) 466 assertEq(t, "map[string]interface{}", `{"a":1,"b":2.1,"c":{"A":10},"d":4}`, string(bytes)) 467 }) 468 }) 469 } 470 471 type mustErrTypeForDebug struct{} 472 473 func (mustErrTypeForDebug) MarshalJSON() ([]byte, error) { 474 panic("panic") 475 return nil, errors.New("panic") 476 } 477 478 func TestDebugMode(t *testing.T) { 479 defer func() { 480 if err := recover(); err == nil { 481 t.Fatal("expected error") 482 } 483 }() 484 var buf bytes.Buffer 485 json.MarshalWithOption(mustErrTypeForDebug{}, json.Debug(), json.DebugWith(&buf)) 486 } 487 488 func TestIssue116(t *testing.T) { 489 t.Run("first", func(t *testing.T) { 490 type Boo struct{ B string } 491 type Struct struct { 492 A int 493 Boo *Boo 494 } 495 type Embedded struct { 496 Struct 497 } 498 b, err := json.Marshal(Embedded{Struct: Struct{ 499 A: 1, 500 Boo: &Boo{B: "foo"}, 501 }}) 502 if err != nil { 503 t.Fatal(err) 504 } 505 expected := `{"A":1,"Boo":{"B":"foo"}}` 506 actual := string(b) 507 if actual != expected { 508 t.Fatalf("expected %s but got %s", expected, actual) 509 } 510 }) 511 t.Run("second", func(t *testing.T) { 512 type Boo struct{ B string } 513 type Struct struct { 514 A int 515 B *Boo 516 } 517 type Embedded struct { 518 Struct 519 } 520 b, err := json.Marshal(Embedded{Struct: Struct{ 521 A: 1, 522 B: &Boo{B: "foo"}, 523 }}) 524 if err != nil { 525 t.Fatal(err) 526 } 527 actual := string(b) 528 expected := `{"A":1,"B":{"B":"foo"}}` 529 if actual != expected { 530 t.Fatalf("expected %s but got %s", expected, actual) 531 } 532 }) 533 } 534 535 type marshalJSON struct{} 536 537 func (*marshalJSON) MarshalJSON() ([]byte, error) { 538 return []byte(`1`), nil 539 } 540 541 func Test_MarshalJSON(t *testing.T) { 542 t.Run("*struct", func(t *testing.T) { 543 bytes, err := json.Marshal(&marshalJSON{}) 544 assertErr(t, err) 545 assertEq(t, "MarshalJSON", "1", string(bytes)) 546 }) 547 t.Run("time", func(t *testing.T) { 548 bytes, err := json.Marshal(time.Time{}) 549 assertErr(t, err) 550 assertEq(t, "MarshalJSON", `"0001-01-01T00:00:00Z"`, string(bytes)) 551 }) 552 } 553 554 func Test_MarshalIndent(t *testing.T) { 555 prefix := "-" 556 indent := "\t" 557 t.Run("struct", func(t *testing.T) { 558 v := struct { 559 A int `json:"a"` 560 B uint `json:"b"` 561 C string `json:"c"` 562 D any `json:"d"` 563 X int `json:"-"` // ignore field 564 a int `json:"aa"` // private field 565 }{ 566 A: -1, 567 B: 1, 568 C: "hello world", 569 D: struct { 570 E bool `json:"e"` 571 }{ 572 E: true, 573 }, 574 } 575 expected, err := stdjson.MarshalIndent(v, prefix, indent) 576 assertErr(t, err) 577 got, err := json.MarshalIndent(v, prefix, indent) 578 assertErr(t, err) 579 assertEq(t, "struct", string(expected), string(got)) 580 }) 581 t.Run("slice", func(t *testing.T) { 582 t.Run("[]int", func(t *testing.T) { 583 bytes, err := json.MarshalIndent([]int{1, 2, 3, 4}, prefix, indent) 584 assertErr(t, err) 585 result := "[\n-\t1,\n-\t2,\n-\t3,\n-\t4\n-]" 586 assertEq(t, "[]int", result, string(bytes)) 587 }) 588 t.Run("[]interface{}", func(t *testing.T) { 589 bytes, err := json.MarshalIndent([]any{1, 2.1, "hello"}, prefix, indent) 590 assertErr(t, err) 591 result := "[\n-\t1,\n-\t2.1,\n-\t\"hello\"\n-]" 592 assertEq(t, "[]interface{}", result, string(bytes)) 593 }) 594 }) 595 596 t.Run("array", func(t *testing.T) { 597 bytes, err := json.MarshalIndent([4]int{1, 2, 3, 4}, prefix, indent) 598 assertErr(t, err) 599 result := "[\n-\t1,\n-\t2,\n-\t3,\n-\t4\n-]" 600 assertEq(t, "array", result, string(bytes)) 601 }) 602 t.Run("map", func(t *testing.T) { 603 t.Run("map[string]int", func(t *testing.T) { 604 bytes, err := json.MarshalIndent(map[string]int{ 605 "a": 1, 606 "b": 2, 607 "c": 3, 608 "d": 4, 609 }, prefix, indent) 610 assertErr(t, err) 611 result := "{\n-\t\"a\": 1,\n-\t\"b\": 2,\n-\t\"c\": 3,\n-\t\"d\": 4\n-}" 612 assertEq(t, "map", result, string(bytes)) 613 }) 614 t.Run("map[string]interface{}", func(t *testing.T) { 615 type T struct { 616 E int 617 F int 618 } 619 v := map[string]any{ 620 "a": 1, 621 "b": 2.1, 622 "c": &T{ 623 E: 10, 624 F: 11, 625 }, 626 "d": 4, 627 } 628 bytes, err := json.MarshalIndent(v, prefix, indent) 629 assertErr(t, err) 630 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-}" 631 assertEq(t, "map[string]interface{}", result, string(bytes)) 632 }) 633 }) 634 } 635 636 type StringTag struct { 637 BoolStr bool `json:",string"` 638 IntStr int64 `json:",string"` 639 UintptrStr uintptr `json:",string"` 640 StrStr string `json:",string"` 641 NumberStr json.Number `json:",string"` 642 } 643 644 func TestRoundtripStringTag(t *testing.T) { 645 tests := []struct { 646 name string 647 in StringTag 648 want string // empty to just test that we roundtrip 649 }{ 650 { 651 name: "AllTypes", 652 in: StringTag{ 653 BoolStr: true, 654 IntStr: 42, 655 UintptrStr: 44, 656 StrStr: "xzbit", 657 NumberStr: "46", 658 }, 659 want: `{ 660 "BoolStr": "true", 661 "IntStr": "42", 662 "UintptrStr": "44", 663 "StrStr": "\"xzbit\"", 664 "NumberStr": "46" 665 }`, 666 }, 667 { 668 // See golang.org/issues/38173. 669 name: "StringDoubleEscapes", 670 in: StringTag{ 671 StrStr: "\b\f\n\r\t\"\\", 672 NumberStr: "0", // just to satisfy the roundtrip 673 }, 674 want: `{ 675 "BoolStr": "false", 676 "IntStr": "0", 677 "UintptrStr": "0", 678 "StrStr": "\"\\u0008\\u000c\\n\\r\\t\\\"\\\\\"", 679 "NumberStr": "0" 680 }`, 681 }, 682 } 683 for _, test := range tests { 684 t.Run(test.name, func(t *testing.T) { 685 // Indent with a tab prefix to make the multi-line string 686 // literals in the table nicer to read. 687 got, err := json.MarshalIndent(&test.in, "\t\t\t", "\t") 688 if err != nil { 689 t.Fatal(err) 690 } 691 if got := string(got); got != test.want { 692 t.Fatalf(" got: %s\nwant: %s\n", got, test.want) 693 } 694 695 // Verify that it round-trips. 696 var s2 StringTag 697 if err := json.Unmarshal(got, &s2); err != nil { 698 t.Fatalf("Decode: %v", err) 699 } 700 if !reflect.DeepEqual(test.in, s2) { 701 t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", test.in, string(got), s2) 702 } 703 }) 704 } 705 } 706 707 // byte slices are special even if they're renamed types. 708 type renamedByte byte 709 710 type renamedByteSlice []byte 711 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 {in: rawNil, want: "null", ok: true}, 757 {in: &rawNil, want: "null", ok: true}, 758 {in: []any{rawNil}, want: "[null]", ok: true}, 759 {in: &[]any{rawNil}, want: "[null]", ok: true}, 760 {in: []any{&rawNil}, want: "[null]", ok: true}, 761 {in: &[]any{&rawNil}, want: "[null]", ok: true}, 762 {in: struct{ M json.RawMessage }{M: rawNil}, want: `{"M":null}`, ok: true}, 763 {in: &struct{ M json.RawMessage }{M: rawNil}, want: `{"M":null}`, ok: true}, 764 {in: struct{ M *json.RawMessage }{M: &rawNil}, want: `{"M":null}`, ok: true}, 765 {in: &struct{ M *json.RawMessage }{M: &rawNil}, want: `{"M":null}`, ok: true}, 766 {in: map[string]any{"M": rawNil}, want: `{"M":null}`, ok: true}, 767 {in: &map[string]any{"M": rawNil}, want: `{"M":null}`, ok: true}, 768 {in: map[string]any{"M": &rawNil}, want: `{"M":null}`, ok: true}, 769 {in: &map[string]any{"M": &rawNil}, want: `{"M":null}`, ok: true}, 770 {in: T1{M: rawNil}, want: "{}", ok: true}, 771 {in: T2{M: &rawNil}, want: `{"M":null}`, ok: true}, 772 {in: &T1{M: rawNil}, want: "{}", ok: true}, 773 {in: &T2{M: &rawNil}, want: `{"M":null}`, ok: true}, 774 775 // Test with empty, but non-nil, RawMessage. 776 {in: rawEmpty, want: "", ok: false}, 777 {in: &rawEmpty, want: "", ok: false}, 778 {in: []any{rawEmpty}, want: "", ok: false}, 779 {in: &[]any{rawEmpty}, want: "", ok: false}, 780 {in: []any{&rawEmpty}, want: "", ok: false}, 781 {in: &[]any{&rawEmpty}, want: "", ok: false}, 782 {in: struct{ X json.RawMessage }{X: rawEmpty}, want: "", ok: false}, 783 {in: &struct{ X json.RawMessage }{X: rawEmpty}, want: "", ok: false}, 784 {in: struct{ X *json.RawMessage }{X: &rawEmpty}, want: "", ok: false}, 785 {in: &struct{ X *json.RawMessage }{X: &rawEmpty}, want: "", ok: false}, 786 {in: map[string]any{"nil": rawEmpty}, want: "", ok: false}, 787 {in: &map[string]any{"nil": rawEmpty}, want: "", ok: false}, 788 {in: map[string]any{"nil": &rawEmpty}, want: "", ok: false}, 789 {in: &map[string]any{"nil": &rawEmpty}, want: "", ok: false}, 790 791 {in: T1{M: rawEmpty}, want: "{}", ok: true}, 792 {in: T2{M: &rawEmpty}, want: "", ok: false}, 793 {in: &T1{M: rawEmpty}, want: "{}", ok: true}, 794 {in: &T2{M: &rawEmpty}, want: "", ok: 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 {in: rawText, want: `"foo"`, ok: true}, // Issue6458 802 {in: &rawText, want: `"foo"`, ok: true}, 803 {in: []any{rawText}, want: `["foo"]`, ok: true}, // Issue6458 804 {in: &[]any{rawText}, want: `["foo"]`, ok: true}, // Issue6458 805 {in: []any{&rawText}, want: `["foo"]`, ok: true}, 806 {in: &[]any{&rawText}, want: `["foo"]`, ok: true}, 807 {in: struct{ M json.RawMessage }{M: rawText}, want: `{"M":"foo"}`, ok: true}, // Issue6458 808 {in: &struct{ M json.RawMessage }{M: rawText}, want: `{"M":"foo"}`, ok: true}, 809 {in: struct{ M *json.RawMessage }{M: &rawText}, want: `{"M":"foo"}`, ok: true}, 810 {in: &struct{ M *json.RawMessage }{M: &rawText}, want: `{"M":"foo"}`, ok: true}, 811 {in: map[string]any{"M": rawText}, want: `{"M":"foo"}`, ok: true}, // Issue6458 812 {in: &map[string]any{"M": rawText}, want: `{"M":"foo"}`, ok: true}, // Issue6458 813 {in: map[string]any{"M": &rawText}, want: `{"M":"foo"}`, ok: true}, 814 {in: &map[string]any{"M": &rawText}, want: `{"M":"foo"}`, ok: true}, 815 {in: T1{M: rawText}, want: `{"M":"foo"}`, ok: true}, // Issue6458 816 {in: T2{M: &rawText}, want: `{"M":"foo"}`, ok: true}, 817 {in: &T1{M: rawText}, want: `{"M":"foo"}`, ok: true}, 818 {in: &T2{M: &rawText}, want: `{"M":"foo"}`, ok: 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 err: json.NewMarshalerError(st, fmt.Errorf(errText), ""), 993 want: "json: error calling MarshalJSON for type " + st.String() + ": " + errText, 994 }, 995 { 996 err: json.NewMarshalerError(st, fmt.Errorf(errText), "TestMarshalerError"), 997 want: "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 pos := bytes.IndexByte(b, ':') 1020 if pos == -1 { 1021 return errors.New("missing separator") 1022 } 1023 u.A, u.B = string(b[:pos]), string(b[pos+1:]) 1024 return nil 1025 } 1026 1027 func TestTextMarshalerMapKeysAreSorted(t *testing.T) { 1028 data := map[unmarshalerText]int{ 1029 {A: "x", B: "y"}: 1, 1030 {A: "y", B: "x"}: 2, 1031 {A: "a", B: "z"}: 3, 1032 {A: "z", B: "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 var encodeStringTests = []struct { 1176 in string 1177 out string 1178 }{ 1179 {in: "\x00", out: `"\u0000"`}, 1180 {in: "\x01", out: `"\u0001"`}, 1181 {in: "\x02", out: `"\u0002"`}, 1182 {in: "\x03", out: `"\u0003"`}, 1183 {in: "\x04", out: `"\u0004"`}, 1184 {in: "\x05", out: `"\u0005"`}, 1185 {in: "\x06", out: `"\u0006"`}, 1186 {in: "\x07", out: `"\u0007"`}, 1187 {in: "\x08", out: `"\u0008"`}, 1188 {in: "\x09", out: `"\t"`}, 1189 {in: "\x0a", out: `"\n"`}, 1190 {in: "\x0b", out: `"\u000b"`}, 1191 {in: "\x0c", out: `"\u000c"`}, 1192 {in: "\x0d", out: `"\r"`}, 1193 {in: "\x0e", out: `"\u000e"`}, 1194 {in: "\x0f", out: `"\u000f"`}, 1195 {in: "\x10", out: `"\u0010"`}, 1196 {in: "\x11", out: `"\u0011"`}, 1197 {in: "\x12", out: `"\u0012"`}, 1198 {in: "\x13", out: `"\u0013"`}, 1199 {in: "\x14", out: `"\u0014"`}, 1200 {in: "\x15", out: `"\u0015"`}, 1201 {in: "\x16", out: `"\u0016"`}, 1202 {in: "\x17", out: `"\u0017"`}, 1203 {in: "\x18", out: `"\u0018"`}, 1204 {in: "\x19", out: `"\u0019"`}, 1205 {in: "\x1a", out: `"\u001a"`}, 1206 {in: "\x1b", out: `"\u001b"`}, 1207 {in: "\x1c", out: `"\u001c"`}, 1208 {in: "\x1d", out: `"\u001d"`}, 1209 {in: "\x1e", out: `"\u001e"`}, 1210 {in: "\x1f", out: `"\u001f"`}, 1211 } 1212 1213 func TestEncodeString(t *testing.T) { 1214 for _, tt := range encodeStringTests { 1215 b, err := json.Marshal(tt.in) 1216 if err != nil { 1217 t.Errorf("Marshal(%q): %v", tt.in, err) 1218 continue 1219 } 1220 out := string(b) 1221 if out != tt.out { 1222 t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out) 1223 } 1224 } 1225 } 1226 1227 type jsonbyte byte 1228 1229 func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) } 1230 1231 type textbyte byte 1232 1233 func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) } 1234 1235 type jsonint int 1236 1237 func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) } 1238 1239 type textint int 1240 1241 func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } 1242 1243 func tenc(format string, a ...any) ([]byte, error) { 1244 var buf bytes.Buffer 1245 fmt.Fprintf(&buf, format, a...) 1246 return buf.Bytes(), nil 1247 } 1248 1249 // Issue 13783 1250 func TestEncodeBytekind(t *testing.T) { 1251 testdata := []struct { 1252 data any 1253 want string 1254 }{ 1255 {data: byte(7), want: "7"}, 1256 {data: jsonbyte(7), want: `{"JB":7}`}, 1257 {data: textbyte(4), want: `"TB:4"`}, 1258 {data: jsonint(5), want: `{"JI":5}`}, 1259 {data: textint(1), want: `"TI:1"`}, 1260 {data: []byte{0, 1}, want: `"AAE="`}, 1261 1262 {data: []jsonbyte{0, 1}, want: `[{"JB":0},{"JB":1}]`}, 1263 {data: [][]jsonbyte{{0, 1}, {3}}, want: `[[{"JB":0},{"JB":1}],[{"JB":3}]]`}, 1264 {data: []textbyte{2, 3}, want: `["TB:2","TB:3"]`}, 1265 1266 {data: []jsonint{5, 4}, want: `[{"JI":5},{"JI":4}]`}, 1267 {data: []textint{9, 3}, want: `["TI:9","TI:3"]`}, 1268 {data: []int{9, 3}, want: `[9,3]`}, 1269 } 1270 for i, d := range testdata { 1271 js, err := json.Marshal(d.data) 1272 if err != nil { 1273 t.Error(err) 1274 continue 1275 } 1276 got, want := string(js), d.want 1277 if got != want { 1278 t.Errorf("%d: got %s, want %s", i, got, want) 1279 } 1280 } 1281 } 1282 1283 // golang.org/issue/8582 1284 func TestEncodePointerString(t *testing.T) { 1285 type stringPointer struct { 1286 N *int64 `json:"n,string"` 1287 } 1288 var n int64 = 42 1289 b, err := json.Marshal(stringPointer{N: &n}) 1290 if err != nil { 1291 t.Fatalf("Marshal: %v", err) 1292 } 1293 if got, want := string(b), `{"n":"42"}`; got != want { 1294 t.Errorf("Marshal = %s, want %s", got, want) 1295 } 1296 var back stringPointer 1297 err = json.Unmarshal(b, &back) 1298 if err != nil { 1299 t.Fatalf("Unmarshal: %v", err) 1300 } 1301 if back.N == nil { 1302 t.Fatalf("Unmarshaled nil N field") 1303 } 1304 if *back.N != 42 { 1305 t.Fatalf("*N = %d; want 42", *back.N) 1306 } 1307 } 1308 1309 type SamePointerNoCycle struct { 1310 Ptr1, Ptr2 *SamePointerNoCycle 1311 } 1312 1313 var samePointerNoCycle = &SamePointerNoCycle{} 1314 1315 type PointerCycle struct { 1316 Ptr *PointerCycle 1317 } 1318 1319 var pointerCycle = &PointerCycle{} 1320 1321 type PointerCycleIndirect struct { 1322 Ptrs []any 1323 } 1324 1325 var pointerCycleIndirect = &PointerCycleIndirect{} 1326 1327 func init() { 1328 ptr := &SamePointerNoCycle{} 1329 samePointerNoCycle.Ptr1 = ptr 1330 samePointerNoCycle.Ptr2 = ptr 1331 1332 pointerCycle.Ptr = pointerCycle 1333 pointerCycleIndirect.Ptrs = []any{pointerCycleIndirect} 1334 } 1335 1336 func TestSamePointerNoCycle(t *testing.T) { 1337 if _, err := json.Marshal(samePointerNoCycle); err != nil { 1338 t.Fatalf("unexpected error: %v", err) 1339 } 1340 } 1341 1342 var unsupportedValues = []any{ 1343 math.NaN(), 1344 math.Inf(-1), 1345 math.Inf(1), 1346 pointerCycle, 1347 pointerCycleIndirect, 1348 } 1349 1350 func TestUnsupportedValues(t *testing.T) { 1351 for _, v := range unsupportedValues { 1352 if _, err := json.Marshal(v); err != nil { 1353 if _, ok := err.(*json.UnsupportedValueError); !ok { 1354 t.Errorf("for %v, got %T want UnsupportedValueError", v, err) 1355 } 1356 } else { 1357 t.Errorf("for %v, expected error", v) 1358 } 1359 } 1360 } 1361 1362 func TestIssue10281(t *testing.T) { 1363 type Foo struct { 1364 N json.Number 1365 } 1366 x := Foo{N: json.Number(`invalid`)} 1367 1368 b, err := json.Marshal(&x) 1369 if err == nil { 1370 t.Errorf("Marshal(&x) = %#q; want error", b) 1371 } 1372 } 1373 1374 func TestHTMLEscape(t *testing.T) { 1375 var b, want bytes.Buffer 1376 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` 1377 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) 1378 json.HTMLEscape(&b, []byte(m)) 1379 if !bytes.Equal(b.Bytes(), want.Bytes()) { 1380 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) 1381 } 1382 } 1383 1384 type BugA struct { 1385 S string 1386 } 1387 1388 type BugB struct { 1389 BugA 1390 S string 1391 } 1392 1393 type BugC struct { 1394 S string 1395 } 1396 1397 // Legal Go: We never use the repeated embedded field (S). 1398 type BugX struct { 1399 A int 1400 BugA 1401 BugB 1402 } 1403 1404 // golang.org/issue/16042. 1405 // Even if a nil interface value is passed in, as long as 1406 // it implements Marshaler, it should be marshaled. 1407 type nilJSONMarshaler string 1408 1409 func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) { 1410 if nm == nil { 1411 return json.Marshal("0zenil0") 1412 } 1413 return json.Marshal("zenil:" + string(*nm)) 1414 } 1415 1416 // golang.org/issue/34235. 1417 // Even if a nil interface value is passed in, as long as 1418 // it implements encoding.TextMarshaler, it should be marshaled. 1419 type nilTextMarshaler string 1420 1421 func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { 1422 if nm == nil { 1423 return []byte("0zenil0"), nil 1424 } 1425 return []byte("zenil:" + string(*nm)), nil 1426 } 1427 1428 // See golang.org/issue/16042 and golang.org/issue/34235. 1429 func TestNilMarshal(t *testing.T) { 1430 testCases := []struct { 1431 v any 1432 want string 1433 }{ 1434 {v: nil, want: `null`}, 1435 {v: new(float64), want: `0`}, 1436 {v: []any(nil), want: `null`}, 1437 {v: []string(nil), want: `null`}, 1438 {v: map[string]string(nil), want: `null`}, 1439 {v: []byte(nil), want: `null`}, 1440 {v: struct{ M string }{M: "gopher"}, want: `{"M":"gopher"}`}, 1441 {v: struct{ M json.Marshaler }{}, want: `{"M":null}`}, 1442 {v: struct{ M json.Marshaler }{M: (*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1443 {v: struct{ M any }{M: (*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, 1444 {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, 1445 {v: struct{ M encoding.TextMarshaler }{M: (*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1446 {v: struct{ M any }{M: (*nilTextMarshaler)(nil)}, want: `{"M":null}`}, 1447 } 1448 1449 for i, tt := range testCases { 1450 out, err := json.Marshal(tt.v) 1451 if err != nil || string(out) != tt.want { 1452 t.Errorf("%d: Marshal(%#v) = %#q, %#v, want %#q, nil", i, tt.v, out, err, tt.want) 1453 continue 1454 } 1455 } 1456 } 1457 1458 // Issue 5245. 1459 func TestEmbeddedBug(t *testing.T) { 1460 v := BugB{ 1461 BugA: BugA{S: "A"}, 1462 S: "B", 1463 } 1464 b, err := json.Marshal(v) 1465 if err != nil { 1466 t.Fatal("Marshal:", err) 1467 } 1468 want := `{"S":"B"}` 1469 got := string(b) 1470 if got != want { 1471 t.Fatalf("Marshal: got %s want %s", got, want) 1472 } 1473 // Now check that the duplicate field, S, does not appear. 1474 x := BugX{ 1475 A: 23, 1476 } 1477 b, err = json.Marshal(x) 1478 if err != nil { 1479 t.Fatal("Marshal:", err) 1480 } 1481 want = `{"A":23}` 1482 got = string(b) 1483 if got != want { 1484 t.Fatalf("Marshal: got %s want %s", got, want) 1485 } 1486 } 1487 1488 type BugD struct { // Same as BugA after tagging. 1489 XXX string `json:"S"` 1490 } 1491 1492 // BugD's tagged S field should dominate BugA's. 1493 type BugY struct { 1494 BugA 1495 BugD 1496 } 1497 1498 // Test that a field with a tag dominates untagged fields. 1499 func TestTaggedFieldDominates(t *testing.T) { 1500 v := BugY{ 1501 BugA: BugA{S: "BugA"}, 1502 BugD: BugD{XXX: "BugD"}, 1503 } 1504 b, err := json.Marshal(v) 1505 if err != nil { 1506 t.Fatal("Marshal:", err) 1507 } 1508 want := `{"S":"BugD"}` 1509 got := string(b) 1510 if got != want { 1511 t.Fatalf("Marshal: got %s want %s", got, want) 1512 } 1513 } 1514 1515 // There are no tags here, so S should not appear. 1516 type BugZ struct { 1517 BugA 1518 BugC 1519 BugY // Contains a tagged S field through BugD; should not dominate. 1520 } 1521 1522 func TestDuplicatedFieldDisappears(t *testing.T) { 1523 v := BugZ{ 1524 BugA: BugA{S: "BugA"}, 1525 BugC: BugC{S: "BugC"}, 1526 BugY: BugY{ 1527 BugA: BugA{S: "nested BugA"}, 1528 BugD: BugD{XXX: "nested BugD"}, 1529 }, 1530 } 1531 b, err := json.Marshal(v) 1532 if err != nil { 1533 t.Fatal("Marshal:", err) 1534 } 1535 want := `{}` 1536 got := string(b) 1537 if got != want { 1538 t.Fatalf("Marshal: got %s want %s", got, want) 1539 } 1540 } 1541 1542 func TestAnonymousFields(t *testing.T) { 1543 tests := []struct { 1544 label string // Test name 1545 makeInput func() any // Function to create input value 1546 want string // Expected JSON output 1547 }{{ 1548 // Both S1 and S2 have a field named X. From the perspective of S, 1549 // it is ambiguous which one X refers to. 1550 // This should not serialize either field. 1551 label: "AmbiguousField", 1552 makeInput: func() any { 1553 type ( 1554 S1 struct{ x, X int } 1555 S2 struct{ x, X int } 1556 S struct { 1557 S1 1558 S2 1559 } 1560 ) 1561 return S{S1: S1{x: 1, X: 2}, S2: S2{x: 3, X: 4}} 1562 }, 1563 want: `{}`, 1564 }, { 1565 label: "DominantField", 1566 // Both S1 and S2 have a field named X, but since S has an X field as 1567 // well, it takes precedence over S1.X and S2.X. 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 x, X int 1576 } 1577 ) 1578 return S{S1: S1{x: 1, X: 2}, S2: S2{x: 3, X: 4}, x: 5, X: 6} 1579 }, 1580 want: `{"X":6}`, 1581 }, { 1582 // Unexported embedded field of non-struct type should not be serialized. 1583 label: "UnexportedEmbeddedInt", 1584 makeInput: func() any { 1585 type ( 1586 myInt int 1587 S struct{ myInt } 1588 ) 1589 return S{myInt: 5} 1590 }, 1591 want: `{}`, 1592 }, { 1593 // Exported embedded field of non-struct type should be serialized. 1594 label: "ExportedEmbeddedInt", 1595 makeInput: func() any { 1596 type ( 1597 MyInt int 1598 S struct{ MyInt } 1599 ) 1600 return S{MyInt: 5} 1601 }, 1602 want: `{"MyInt":5}`, 1603 }, { 1604 // Unexported embedded field of pointer to non-struct type 1605 // should not be serialized. 1606 label: "UnexportedEmbeddedIntPointer", 1607 makeInput: func() any { 1608 type ( 1609 myInt int 1610 S struct{ *myInt } 1611 ) 1612 s := S{myInt: new(myInt)} 1613 *s.myInt = 5 1614 return s 1615 }, 1616 want: `{}`, 1617 }, { 1618 // Exported embedded field of pointer to non-struct type 1619 // should be serialized. 1620 label: "ExportedEmbeddedIntPointer", 1621 makeInput: func() any { 1622 type ( 1623 MyInt int 1624 S struct{ *MyInt } 1625 ) 1626 s := S{MyInt: new(MyInt)} 1627 *s.MyInt = 5 1628 return s 1629 }, 1630 want: `{"MyInt":5}`, 1631 }, { 1632 // Exported fields of embedded structs should have their 1633 // exported fields be serialized regardless of whether the struct types 1634 // themselves are exported. 1635 label: "EmbeddedStruct", 1636 makeInput: func() any { 1637 type ( 1638 s1 struct{ x, X int } 1639 S2 struct{ y, Y int } 1640 S struct { 1641 s1 1642 S2 1643 } 1644 ) 1645 return S{s1: s1{x: 1, X: 2}, S2: S2{y: 3, Y: 4}} 1646 }, 1647 want: `{"X":2,"Y":4}`, 1648 }, { 1649 // Exported fields of pointers to embedded structs should have their 1650 // exported fields be serialized regardless of whether the struct types 1651 // themselves are exported. 1652 label: "EmbeddedStructPointer", 1653 makeInput: func() any { 1654 type ( 1655 s1 struct{ x, X int } 1656 S2 struct{ y, Y int } 1657 S struct { 1658 *s1 1659 *S2 1660 } 1661 ) 1662 return S{s1: &s1{x: 1, X: 2}, S2: &S2{y: 3, Y: 4}} 1663 }, 1664 want: `{"X":2,"Y":4}`, 1665 }, { 1666 // Exported fields on embedded unexported structs at multiple levels 1667 // of nesting should still be serialized. 1668 label: "NestedStructAndInts", 1669 makeInput: func() any { 1670 type ( 1671 MyInt1 int 1672 MyInt2 int 1673 myInt int 1674 s2 struct { 1675 MyInt2 1676 myInt 1677 } 1678 s1 struct { 1679 MyInt1 1680 myInt 1681 s2 1682 } 1683 S struct { 1684 s1 1685 myInt 1686 } 1687 ) 1688 return S{s1: s1{MyInt1: 1, myInt: 2, s2: s2{MyInt2: 3, myInt: 4}}, myInt: 6} 1689 }, 1690 want: `{"MyInt1":1,"MyInt2":3}`, 1691 }, { 1692 // If an anonymous struct pointer field is nil, we should ignore 1693 // the embedded fields behind it. Not properly doing so may 1694 // result in the wrong output or reflect panics. 1695 label: "EmbeddedFieldBehindNilPointer", 1696 makeInput: func() any { 1697 type ( 1698 S2 struct{ Field string } 1699 S struct{ *S2 } 1700 ) 1701 return S{} 1702 }, 1703 want: `{}`, 1704 }} 1705 1706 for i, tt := range tests { 1707 t.Run(tt.label, func(t *testing.T) { 1708 b, err := json.Marshal(tt.makeInput()) 1709 if err != nil { 1710 t.Fatalf("%d: Marshal() = %v, want nil error", i, err) 1711 } 1712 if string(b) != tt.want { 1713 t.Fatalf("%d: Marshal() = %q, want %q", i, b, tt.want) 1714 } 1715 }) 1716 } 1717 } 1718 1719 type Optionals struct { 1720 Sr string `json:"sr"` 1721 So string `json:"so,omitempty"` 1722 Sw string `json:"-"` 1723 1724 Ir int `json:"omitempty"` // actually named omitempty, not an option 1725 Io int `json:"io,omitempty"` 1726 1727 Slr []string `json:"slr,random"` 1728 Slo []string `json:"slo,omitempty"` 1729 1730 Mr map[string]any `json:"mr"` 1731 Mo map[string]any `json:",omitempty"` 1732 1733 Fr float64 `json:"fr"` 1734 Fo float64 `json:"fo,omitempty"` 1735 1736 Br bool `json:"br"` 1737 Bo bool `json:"bo,omitempty"` 1738 1739 Ur uint `json:"ur"` 1740 Uo uint `json:"uo,omitempty"` 1741 1742 Str struct{} `json:"str"` 1743 Sto struct{} `json:"sto,omitempty"` 1744 } 1745 1746 var optionalsExpected = `{ 1747 "sr": "", 1748 "omitempty": 0, 1749 "slr": null, 1750 "mr": {}, 1751 "fr": 0, 1752 "br": false, 1753 "ur": 0, 1754 "str": {}, 1755 "sto": {} 1756 }` 1757 1758 func TestOmitEmpty(t *testing.T) { 1759 var o Optionals 1760 o.Sw = "something" 1761 o.Mr = map[string]any{} 1762 o.Mo = map[string]any{} 1763 1764 got, err := json.MarshalIndent(&o, "", " ") 1765 if err != nil { 1766 t.Fatal(err) 1767 } 1768 if got := string(got); got != optionalsExpected { 1769 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) 1770 } 1771 } 1772 1773 type testNullStr string 1774 1775 func (v *testNullStr) MarshalJSON() ([]byte, error) { 1776 if *v == "" { 1777 return []byte("null"), nil 1778 } 1779 1780 return []byte(*v), nil 1781 } 1782 1783 func TestIssue147(t *testing.T) { 1784 type T struct { 1785 Field1 string `json:"field1"` 1786 Field2 testNullStr `json:"field2,omitempty"` 1787 } 1788 got, err := json.Marshal(T{ 1789 Field1: "a", 1790 Field2: "b", 1791 }) 1792 if err != nil { 1793 t.Fatal(err) 1794 } 1795 expect, _ := stdjson.Marshal(T{ 1796 Field1: "a", 1797 Field2: "b", 1798 }) 1799 if !bytes.Equal(expect, got) { 1800 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1801 } 1802 } 1803 1804 type testIssue144 struct { 1805 name string 1806 number int64 1807 } 1808 1809 func (v *testIssue144) MarshalJSON() ([]byte, error) { 1810 if v.name != "" { 1811 return json.Marshal(v.name) 1812 } 1813 return json.Marshal(v.number) 1814 } 1815 1816 func TestIssue144(t *testing.T) { 1817 type Embeded struct { 1818 Field *testIssue144 `json:"field,omitempty"` 1819 } 1820 type T struct { 1821 Embeded 1822 } 1823 { 1824 v := T{ 1825 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1826 } 1827 got, err := json.Marshal(v) 1828 if err != nil { 1829 t.Fatal(err) 1830 } 1831 expect, _ := stdjson.Marshal(v) 1832 if !bytes.Equal(expect, got) { 1833 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1834 } 1835 } 1836 { 1837 v := &T{ 1838 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1839 } 1840 got, err := json.Marshal(v) 1841 if err != nil { 1842 t.Fatal(err) 1843 } 1844 expect, _ := stdjson.Marshal(v) 1845 if !bytes.Equal(expect, got) { 1846 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1847 } 1848 } 1849 } 1850 1851 func TestIssue118(t *testing.T) { 1852 type data struct { 1853 Columns []string `json:"columns"` 1854 Rows1 [][]string `json:"rows1"` 1855 Rows2 [][]string `json:"rows2"` 1856 } 1857 v := data{Columns: []string{"1", "2", "3"}} 1858 got, err := json.MarshalIndent(v, "", " ") 1859 if err != nil { 1860 t.Fatal(err) 1861 } 1862 expect, _ := stdjson.MarshalIndent(v, "", " ") 1863 if !bytes.Equal(expect, got) { 1864 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1865 } 1866 } 1867 1868 func TestIssue104(t *testing.T) { 1869 type A struct { 1870 Field1 string 1871 Field2 int 1872 Field3 float64 1873 } 1874 type T struct { 1875 Field A 1876 } 1877 got, err := json.Marshal(T{}) 1878 if err != nil { 1879 t.Fatal(err) 1880 } 1881 expect, _ := stdjson.Marshal(T{}) 1882 if !bytes.Equal(expect, got) { 1883 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1884 } 1885 } 1886 1887 func TestIssue179(t *testing.T) { 1888 data := ` 1889 { 1890 "t": { 1891 "t1": false, 1892 "t2": 0, 1893 "t3": "", 1894 "t4": [], 1895 "t5": null, 1896 "t6": null 1897 } 1898 }` 1899 type T struct { 1900 X struct { 1901 T1 bool `json:"t1,omitempty"` 1902 T2 float64 `json:"t2,omitempty"` 1903 T3 string `json:"t3,omitempty"` 1904 T4 []string `json:"t4,omitempty"` 1905 T5 *struct{} `json:"t5,omitempty"` 1906 T6 any `json:"t6,omitempty"` 1907 } `json:"x"` 1908 } 1909 var v T 1910 if err := stdjson.Unmarshal([]byte(data), &v); err != nil { 1911 t.Fatal(err) 1912 } 1913 var v2 T 1914 if err := json.Unmarshal([]byte(data), &v2); err != nil { 1915 t.Fatal(err) 1916 } 1917 if !reflect.DeepEqual(v, v2) { 1918 t.Fatalf("failed to decode: expected %v got %v", v, v2) 1919 } 1920 b1, err := stdjson.Marshal(v) 1921 if err != nil { 1922 t.Fatal(err) 1923 } 1924 b2, err := json.Marshal(v2) 1925 if err != nil { 1926 t.Fatal(err) 1927 } 1928 if !bytes.Equal(b1, b2) { 1929 t.Fatalf("failed to equal encoded result: expected %q but got %q", b1, b2) 1930 } 1931 } 1932 1933 func TestIssue180(t *testing.T) { 1934 v := struct { 1935 T struct { 1936 T1 bool `json:"t1"` 1937 T2 float64 `json:"t2"` 1938 T3 string `json:"t3"` 1939 T4 []string `json:"t4"` 1940 T5 *struct{} `json:"t5"` 1941 T6 any `json:"t6"` 1942 T7 [][]string `json:"t7"` 1943 } `json:"t"` 1944 }{ 1945 T: struct { 1946 T1 bool `json:"t1"` 1947 T2 float64 `json:"t2"` 1948 T3 string `json:"t3"` 1949 T4 []string `json:"t4"` 1950 T5 *struct{} `json:"t5"` 1951 T6 any `json:"t6"` 1952 T7 [][]string `json:"t7"` 1953 }{ 1954 T4: []string{}, 1955 T7: [][]string{ 1956 {""}, 1957 {"hello", "world"}, 1958 {}, 1959 }, 1960 }, 1961 } 1962 b1, err := stdjson.MarshalIndent(v, "", "\t") 1963 if err != nil { 1964 t.Fatal(err) 1965 } 1966 b2, err := json.MarshalIndent(v, "", "\t") 1967 if err != nil { 1968 t.Fatal(err) 1969 } 1970 if !bytes.Equal(b1, b2) { 1971 t.Fatalf("failed to equal encoded result: expected %s but got %s", string(b1), string(b2)) 1972 } 1973 } 1974 1975 func TestIssue235(t *testing.T) { 1976 type TaskMessage struct { 1977 Type string 1978 Payload map[string]any 1979 UniqueKey string 1980 } 1981 msg := TaskMessage{ 1982 Payload: map[string]any{ 1983 "sent_at": map[string]any{ 1984 "Time": "0001-01-01T00:00:00Z", 1985 "Valid": false, 1986 }, 1987 }, 1988 } 1989 if _, err := json.Marshal(msg); err != nil { 1990 t.Fatal(err) 1991 } 1992 } 1993 1994 func TestEncodeMapKeyTypeInterface(t *testing.T) { 1995 if _, err := json.Marshal(map[any]any{"a": 1}); err == nil { 1996 t.Fatal("expected error") 1997 } 1998 } 1999 2000 type marshalContextKey struct{} 2001 2002 type marshalContextStructType struct{} 2003 2004 func (t *marshalContextStructType) MarshalJSON(ctx context.Context) ([]byte, error) { 2005 v := ctx.Value(marshalContextKey{}) 2006 s, ok := v.(string) 2007 if !ok { 2008 return nil, errors.New("failed to propagate parent context.Context") 2009 } 2010 if s != "hello" { 2011 return nil, errors.New("failed to propagate parent context.Context") 2012 } 2013 return []byte(`"success"`), nil 2014 } 2015 2016 func TestEncodeContextOption(t *testing.T) { 2017 t.Run("MarshalContext", func(t *testing.T) { 2018 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2019 b, err := json.MarshalContext(ctx, &marshalContextStructType{}) 2020 if err != nil { 2021 t.Fatal(err) 2022 } 2023 if string(b) != `"success"` { 2024 t.Fatal("failed to encode with MarshalerContext") 2025 } 2026 }) 2027 t.Run("EncodeContext", func(t *testing.T) { 2028 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2029 buf := bytes.NewBuffer([]byte{}) 2030 if err := json.NewEncoder(buf).EncodeContext(ctx, &marshalContextStructType{}); err != nil { 2031 t.Fatal(err) 2032 } 2033 if buf.String() != "\"success\"\n" { 2034 t.Fatal("failed to encode with EncodeContext") 2035 } 2036 }) 2037 } 2038 2039 func TestInterfaceWithPointer(t *testing.T) { 2040 var ( 2041 ivalue int = 10 2042 uvalue uint = 20 2043 svalue string = "value" 2044 bvalue bool = true 2045 fvalue float32 = 3.14 2046 nvalue json.Number = "1.23" 2047 structv = struct{ A int }{A: 10} 2048 slice = []int{1, 2, 3, 4} 2049 array = [4]int{1, 2, 3, 4} 2050 mapvalue = map[string]int{"a": 1} 2051 ) 2052 data := map[string]any{ 2053 "ivalue": ivalue, 2054 "uvalue": uvalue, 2055 "svalue": svalue, 2056 "bvalue": bvalue, 2057 "fvalue": fvalue, 2058 "nvalue": nvalue, 2059 "struct": structv, 2060 "slice": slice, 2061 "array": array, 2062 "map": mapvalue, 2063 "pivalue": &ivalue, 2064 "puvalue": &uvalue, 2065 "psvalue": &svalue, 2066 "pbvalue": &bvalue, 2067 "pfvalue": &fvalue, 2068 "pnvalue": &nvalue, 2069 "pstruct": &structv, 2070 "pslice": &slice, 2071 "parray": &array, 2072 "pmap": &mapvalue, 2073 } 2074 expected, err := stdjson.Marshal(data) 2075 if err != nil { 2076 t.Fatal(err) 2077 } 2078 actual, err := json.Marshal(data) 2079 if err != nil { 2080 t.Fatal(err) 2081 } 2082 assertEq(t, "interface{}", string(expected), string(actual)) 2083 } 2084 2085 func TestIssue263(t *testing.T) { 2086 type Foo struct { 2087 A []string `json:"a"` 2088 B int `json:"b"` 2089 } 2090 2091 type MyStruct struct { 2092 Foo *Foo `json:"foo,omitempty"` 2093 } 2094 2095 s := MyStruct{ 2096 Foo: &Foo{ 2097 A: []string{"ls -lah"}, 2098 B: 0, 2099 }, 2100 } 2101 expected, err := stdjson.Marshal(s) 2102 if err != nil { 2103 t.Fatal(err) 2104 } 2105 actual, err := json.Marshal(s) 2106 if err != nil { 2107 t.Fatal(err) 2108 } 2109 if !bytes.Equal(expected, actual) { 2110 t.Fatalf("expected:[%s] but got:[%s]", string(expected), string(actual)) 2111 } 2112 } 2113 2114 func TestEmbeddedNotFirstField(t *testing.T) { 2115 type Embedded struct { 2116 Has bool `json:"has"` 2117 } 2118 type T struct { 2119 X int `json:"is"` 2120 Embedded `json:"child"` 2121 } 2122 p := T{X: 10, Embedded: Embedded{Has: true}} 2123 expected, err := stdjson.Marshal(&p) 2124 if err != nil { 2125 t.Fatal(err) 2126 } 2127 got, err := json.Marshal(&p) 2128 if err != nil { 2129 t.Fatal(err) 2130 } 2131 if !bytes.Equal(expected, got) { 2132 t.Fatalf("failed to encode embedded structure. expected = %q but got %q", expected, got) 2133 } 2134 } 2135 2136 type implementedMethodIface interface { 2137 M() 2138 } 2139 2140 type implementedIfaceType struct { 2141 A int 2142 B string 2143 } 2144 2145 func (implementedIfaceType) M() {} 2146 2147 func TestImplementedMethodInterfaceType(t *testing.T) { 2148 data := []implementedIfaceType{{}} 2149 expected, err := stdjson.Marshal(data) 2150 if err != nil { 2151 t.Fatal(err) 2152 } 2153 got, err := json.Marshal(data) 2154 if err != nil { 2155 t.Fatal(err) 2156 } 2157 if !bytes.Equal(expected, got) { 2158 t.Fatalf("failed to encode implemented method interface type. expected:[%q] but got:[%q]", expected, got) 2159 } 2160 } 2161 2162 func TestEmptyStructInterface(t *testing.T) { 2163 expected, err := stdjson.Marshal([]any{struct{}{}}) 2164 if err != nil { 2165 t.Fatal(err) 2166 } 2167 got, err := json.Marshal([]any{struct{}{}}) 2168 if err != nil { 2169 t.Fatal(err) 2170 } 2171 if !bytes.Equal(expected, got) { 2172 t.Fatalf("failed to encode empty struct interface. expected:[%q] but got:[%q]", expected, got) 2173 } 2174 } 2175 2176 func TestIssue290(t *testing.T) { 2177 type Issue290 interface { 2178 A() 2179 } 2180 var a struct { 2181 A Issue290 2182 } 2183 expected, err := stdjson.Marshal(a) 2184 if err != nil { 2185 t.Fatal(err) 2186 } 2187 got, err := json.Marshal(a) 2188 if err != nil { 2189 t.Fatal(err) 2190 } 2191 if !bytes.Equal(expected, got) { 2192 t.Fatalf("failed to encode non empty interface. expected = %q but got %q", expected, got) 2193 } 2194 } 2195 2196 func TestIssue299(t *testing.T) { 2197 t.Run("conflict second field", func(t *testing.T) { 2198 type Embedded struct { 2199 ID string `json:"id"` 2200 Name map[string]string `json:"name"` 2201 } 2202 type Container struct { 2203 Embedded 2204 Name string `json:"name"` 2205 } 2206 c := &Container{ 2207 Embedded: Embedded{ 2208 ID: "1", 2209 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2210 }, 2211 Name: "Hi", 2212 } 2213 expected, _ := stdjson.Marshal(c) 2214 got, err := json.Marshal(c) 2215 if err != nil { 2216 t.Fatal(err) 2217 } 2218 if !bytes.Equal(expected, got) { 2219 t.Fatalf("expected %q but got %q", expected, got) 2220 } 2221 }) 2222 t.Run("conflict map field", func(t *testing.T) { 2223 type Embedded struct { 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 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2233 }, 2234 Name: "Hi", 2235 } 2236 expected, _ := stdjson.Marshal(c) 2237 got, err := json.Marshal(c) 2238 if err != nil { 2239 t.Fatal(err) 2240 } 2241 if !bytes.Equal(expected, got) { 2242 t.Fatalf("expected %q but got %q", expected, got) 2243 } 2244 }) 2245 t.Run("conflict slice field", func(t *testing.T) { 2246 type Embedded struct { 2247 Name []string `json:"name"` 2248 } 2249 type Container struct { 2250 Embedded 2251 Name string `json:"name"` 2252 } 2253 c := &Container{ 2254 Embedded: Embedded{ 2255 Name: []string{"Hello"}, 2256 }, 2257 Name: "Hi", 2258 } 2259 expected, _ := stdjson.Marshal(c) 2260 got, err := json.Marshal(c) 2261 if err != nil { 2262 t.Fatal(err) 2263 } 2264 if !bytes.Equal(expected, got) { 2265 t.Fatalf("expected %q but got %q", expected, got) 2266 } 2267 }) 2268 } 2269 2270 func TestRecursivePtrHead(t *testing.T) { 2271 type User struct { 2272 Account *string `json:"account"` 2273 Password *string `json:"password"` 2274 Nickname *string `json:"nickname"` 2275 Address *string `json:"address,omitempty"` 2276 Friends []*User `json:"friends,omitempty"` 2277 } 2278 user1Account, user1Password, user1Nickname := "abcdef", "123456", "user1" 2279 user1 := &User{ 2280 Account: &user1Account, 2281 Password: &user1Password, 2282 Nickname: &user1Nickname, 2283 Address: nil, 2284 } 2285 user2Account, user2Password, user2Nickname := "ghijkl", "123456", "user2" 2286 user2 := &User{ 2287 Account: &user2Account, 2288 Password: &user2Password, 2289 Nickname: &user2Nickname, 2290 Address: nil, 2291 } 2292 user1.Friends = []*User{user2} 2293 expected, err := stdjson.Marshal(user1) 2294 if err != nil { 2295 t.Fatal(err) 2296 } 2297 got, err := json.Marshal(user1) 2298 if err != nil { 2299 t.Fatal(err) 2300 } 2301 if !bytes.Equal(expected, got) { 2302 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2303 } 2304 } 2305 2306 func TestMarshalIndent(t *testing.T) { 2307 v := map[string]map[string]any{ 2308 "a": { 2309 "b": "1", 2310 "c": map[string]any{ 2311 "d": "1", 2312 }, 2313 }, 2314 } 2315 expected, err := stdjson.MarshalIndent(v, "", " ") 2316 if err != nil { 2317 t.Fatal(err) 2318 } 2319 got, err := json.MarshalIndent(v, "", " ") 2320 if err != nil { 2321 t.Fatal(err) 2322 } 2323 if !bytes.Equal(expected, got) { 2324 t.Fatalf("expected: %q but got %q", expected, got) 2325 } 2326 } 2327 2328 type issue318Embedded struct { 2329 _ [64]byte 2330 } 2331 2332 type issue318 struct { 2333 issue318Embedded `json:"-"` 2334 ID issue318MarshalText `json:"id,omitempty"` 2335 } 2336 2337 type issue318MarshalText struct { 2338 ID string 2339 } 2340 2341 func (i issue318MarshalText) MarshalText() ([]byte, error) { 2342 return []byte(i.ID), nil 2343 } 2344 2345 func TestIssue318(t *testing.T) { 2346 v := issue318{ 2347 ID: issue318MarshalText{ID: "1"}, 2348 } 2349 b, err := json.Marshal(v) 2350 if err != nil { 2351 t.Fatal(err) 2352 } 2353 expected := `{"id":"1"}` 2354 if string(b) != expected { 2355 t.Fatalf("failed to encode. expected %s but got %s", expected, string(b)) 2356 } 2357 } 2358 2359 type emptyStringMarshaler struct { 2360 Value stringMarshaler `json:"value,omitempty"` 2361 } 2362 2363 type stringMarshaler string 2364 2365 func (s stringMarshaler) MarshalJSON() ([]byte, error) { 2366 return []byte(`"` + s + `"`), nil 2367 } 2368 2369 func TestEmptyStringMarshaler(t *testing.T) { 2370 value := emptyStringMarshaler{} 2371 expected, err := stdjson.Marshal(value) 2372 assertErr(t, err) 2373 got, err := json.Marshal(value) 2374 assertErr(t, err) 2375 assertEq(t, "struct", string(expected), string(got)) 2376 } 2377 2378 func TestIssue324(t *testing.T) { 2379 type T struct { 2380 FieldA *string `json:"fieldA,omitempty"` 2381 FieldB *string `json:"fieldB,omitempty"` 2382 FieldC *bool `json:"fieldC"` 2383 FieldD []string `json:"fieldD,omitempty"` 2384 } 2385 v := &struct { 2386 Code string `json:"code"` 2387 *T 2388 }{ 2389 T: &T{}, 2390 } 2391 var sv = "Test Field" 2392 v.Code = "Test" 2393 v.T.FieldB = &sv 2394 expected, err := stdjson.Marshal(v) 2395 if err != nil { 2396 t.Fatal(err) 2397 } 2398 got, err := json.Marshal(v) 2399 if err != nil { 2400 t.Fatal(err) 2401 } 2402 if !bytes.Equal(expected, got) { 2403 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2404 } 2405 } 2406 2407 func TestIssue339(t *testing.T) { 2408 type T1 struct { 2409 *big.Int 2410 } 2411 type T2 struct { 2412 T1 T1 `json:"T1"` 2413 } 2414 v := T2{T1: T1{Int: big.NewInt(10000)}} 2415 b, err := json.Marshal(&v) 2416 assertErr(t, err) 2417 got := string(b) 2418 expected := `{"T1":10000}` 2419 if got != expected { 2420 t.Errorf("unexpected result: %v != %v", got, expected) 2421 } 2422 } 2423 2424 func TestIssue376(t *testing.T) { 2425 type Container struct { 2426 V any `json:"value"` 2427 } 2428 type MapOnly struct { 2429 Map map[string]int64 `json:"map"` 2430 } 2431 b, err := json.Marshal(Container{V: MapOnly{}}) 2432 if err != nil { 2433 t.Fatal(err) 2434 } 2435 got := string(b) 2436 expected := `{"value":{"map":null}}` 2437 if got != expected { 2438 t.Errorf("unexpected result: %v != %v", got, expected) 2439 } 2440 } 2441 2442 type Issue370 struct { 2443 String string 2444 Valid bool 2445 } 2446 2447 func (i *Issue370) MarshalJSON() ([]byte, error) { 2448 if !i.Valid { 2449 return json.Marshal(nil) 2450 } 2451 return json.Marshal(i.String) 2452 } 2453 2454 func TestIssue370(t *testing.T) { 2455 v := []struct { 2456 V Issue370 2457 }{ 2458 {V: Issue370{String: "test", Valid: true}}, 2459 } 2460 b, err := json.Marshal(v) 2461 if err != nil { 2462 t.Fatal(err) 2463 } 2464 got := string(b) 2465 expected := `[{"V":"test"}]` 2466 if got != expected { 2467 t.Errorf("unexpected result: %v != %v", got, expected) 2468 } 2469 } 2470 2471 func TestIssue374(t *testing.T) { 2472 r := io.MultiReader(strings.NewReader(strings.Repeat(" ", 505)+`"\u`), strings.NewReader(`0000"`)) 2473 var v any 2474 if err := json.NewDecoder(r).Decode(&v); err != nil { 2475 t.Fatal(err) 2476 } 2477 got := v.(string) 2478 expected := "\u0000" 2479 if got != expected { 2480 t.Errorf("unexpected result: %q != %q", got, expected) 2481 } 2482 } 2483 2484 func TestIssue381(t *testing.T) { 2485 var v struct { 2486 Field0 bool 2487 Field1 bool 2488 Field2 bool 2489 Field3 bool 2490 Field4 bool 2491 Field5 bool 2492 Field6 bool 2493 Field7 bool 2494 Field8 bool 2495 Field9 bool 2496 Field10 bool 2497 Field11 bool 2498 Field12 bool 2499 Field13 bool 2500 Field14 bool 2501 Field15 bool 2502 Field16 bool 2503 Field17 bool 2504 Field18 bool 2505 Field19 bool 2506 Field20 bool 2507 Field21 bool 2508 Field22 bool 2509 Field23 bool 2510 Field24 bool 2511 Field25 bool 2512 Field26 bool 2513 Field27 bool 2514 Field28 bool 2515 Field29 bool 2516 Field30 bool 2517 Field31 bool 2518 Field32 bool 2519 Field33 bool 2520 Field34 bool 2521 Field35 bool 2522 Field36 bool 2523 Field37 bool 2524 Field38 bool 2525 Field39 bool 2526 Field40 bool 2527 Field41 bool 2528 Field42 bool 2529 Field43 bool 2530 Field44 bool 2531 Field45 bool 2532 Field46 bool 2533 Field47 bool 2534 Field48 bool 2535 Field49 bool 2536 Field50 bool 2537 Field51 bool 2538 Field52 bool 2539 Field53 bool 2540 Field54 bool 2541 Field55 bool 2542 Field56 bool 2543 Field57 bool 2544 Field58 bool 2545 Field59 bool 2546 Field60 bool 2547 Field61 bool 2548 Field62 bool 2549 Field63 bool 2550 Field64 bool 2551 Field65 bool 2552 Field66 bool 2553 Field67 bool 2554 Field68 bool 2555 Field69 bool 2556 Field70 bool 2557 Field71 bool 2558 Field72 bool 2559 Field73 bool 2560 Field74 bool 2561 Field75 bool 2562 Field76 bool 2563 Field77 bool 2564 Field78 bool 2565 Field79 bool 2566 Field80 bool 2567 Field81 bool 2568 Field82 bool 2569 Field83 bool 2570 Field84 bool 2571 Field85 bool 2572 Field86 bool 2573 Field87 bool 2574 Field88 bool 2575 Field89 bool 2576 Field90 bool 2577 Field91 bool 2578 Field92 bool 2579 Field93 bool 2580 Field94 bool 2581 Field95 bool 2582 Field96 bool 2583 Field97 bool 2584 Field98 bool 2585 Field99 bool 2586 } 2587 2588 // test encoder cache issue, not related to encoder 2589 b, err := json.Marshal(v) 2590 if err != nil { 2591 t.Errorf("failed to marshal %s", err.Error()) 2592 t.FailNow() 2593 } 2594 2595 std, err := stdjson.Marshal(v) 2596 if err != nil { 2597 t.Errorf("failed to marshal with encoding/json %s", err.Error()) 2598 t.FailNow() 2599 } 2600 2601 if !bytes.Equal(std, b) { 2602 t.Errorf("encoding result not equal to encoding/json") 2603 t.FailNow() 2604 } 2605 } 2606 2607 func TestIssue386(t *testing.T) { 2608 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)"}` 2609 var a struct { 2610 Date *string `json:"date"` 2611 Platform *string `json:"platform"` 2612 Summary string `json:"summary"` 2613 Name string `json:"name"` 2614 } 2615 err := json.NewDecoder(strings.NewReader(raw)).Decode(&a) 2616 if err != nil { 2617 t.Error(err) 2618 } 2619 } 2620 2621 type customMapKey string 2622 2623 func (b customMapKey) MarshalJSON() ([]byte, error) { 2624 return []byte("[]"), nil 2625 } 2626 2627 func TestCustomMarshalForMapKey(t *testing.T) { 2628 m := map[customMapKey]string{customMapKey("skipcustom"): "test"} 2629 expected, err := stdjson.Marshal(m) 2630 assertErr(t, err) 2631 got, err := json.Marshal(m) 2632 assertErr(t, err) 2633 assertEq(t, "custom map key", string(expected), string(got)) 2634 } 2635 2636 func TestIssue391(t *testing.T) { 2637 type A struct { 2638 X string `json:"x,omitempty"` 2639 } 2640 type B struct { 2641 A 2642 } 2643 type C struct { 2644 X []int `json:"x,omitempty"` 2645 } 2646 for _, tc := range []struct { 2647 name string 2648 in any 2649 out string 2650 }{ 2651 {in: struct{ B }{}, out: "{}"}, 2652 {in: struct { 2653 B 2654 Y string `json:"y"` 2655 }{}, out: `{"y":""}`}, 2656 {in: struct { 2657 Y string `json:"y"` 2658 B 2659 }{}, out: `{"y":""}`}, 2660 {in: struct{ C }{}, out: "{}"}, 2661 } { 2662 t.Run(tc.name, func(t *testing.T) { 2663 b, err := json.Marshal(tc.in) 2664 assertErr(t, err) 2665 assertEq(t, "unexpected result", tc.out, string(b)) 2666 }) 2667 } 2668 } 2669 2670 func TestIssue417(t *testing.T) { 2671 x := map[string]string{ 2672 "b": "b", 2673 "a": "a", 2674 } 2675 b, err := json.MarshalIndentWithOption(x, "", " ", json.UnorderedMap()) 2676 assertErr(t, err) 2677 2678 var y map[string]string 2679 err = json.Unmarshal(b, &y) 2680 assertErr(t, err) 2681 2682 assertEq(t, "key b", "b", y["b"]) 2683 assertEq(t, "key a", "a", y["a"]) 2684 } 2685 2686 func TestIssue426(t *testing.T) { 2687 type I interface { 2688 Foo() 2689 } 2690 type A struct { 2691 I 2692 Val string 2693 } 2694 var s A 2695 s.Val = "456" 2696 2697 b, _ := json.Marshal(s) 2698 assertEq(t, "unexpected result", `{"I":null,"Val":"456"}`, string(b)) 2699 } 2700 2701 func TestIssue441(t *testing.T) { 2702 type A struct { 2703 Y string `json:"y,omitempty"` 2704 } 2705 2706 type B struct { 2707 X *int `json:"x,omitempty"` 2708 A 2709 Z int `json:"z,omitempty"` 2710 } 2711 2712 b, err := json.Marshal(B{}) 2713 assertErr(t, err) 2714 assertEq(t, "unexpected result", "{}", string(b)) 2715 }