github.com/night-codes/go-json@v0.9.15/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 "reflect" 15 "regexp" 16 "strconv" 17 "strings" 18 "testing" 19 "time" 20 21 "github.com/night-codes/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]interface{} `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]interface{} `json:"b"` 380 }) 381 v.B = map[string]interface{}{"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("[]interface{}", func(t *testing.T) { 425 bytes, err := json.Marshal([]interface{}{1, 2.1, "hello"}) 426 assertErr(t, err) 427 assertEq(t, "[]interface{}", `[1,2.1,"hello"]`, string(bytes)) 428 }) 429 }) 430 431 t.Run("array", func(t *testing.T) { 432 bytes, err := json.Marshal([4]int{1, 2, 3, 4}) 433 assertErr(t, err) 434 assertEq(t, "array", `[1,2,3,4]`, string(bytes)) 435 }) 436 t.Run("map", func(t *testing.T) { 437 t.Run("map[string]int", func(t *testing.T) { 438 v := map[string]int{ 439 "a": 1, 440 "b": 2, 441 "c": 3, 442 "d": 4, 443 } 444 bytes, err := json.Marshal(v) 445 assertErr(t, err) 446 assertEq(t, "map", `{"a":1,"b":2,"c":3,"d":4}`, string(bytes)) 447 b, err := json.MarshalWithOption(v, json.UnorderedMap()) 448 assertErr(t, err) 449 assertEq(t, "unordered map", len(`{"a":1,"b":2,"c":3,"d":4}`), len(string(b))) 450 }) 451 t.Run("map[string]interface{}", func(t *testing.T) { 452 type T struct { 453 A int 454 } 455 v := map[string]interface{}{ 456 "a": 1, 457 "b": 2.1, 458 "c": &T{ 459 A: 10, 460 }, 461 "d": 4, 462 } 463 bytes, err := json.Marshal(v) 464 assertErr(t, err) 465 assertEq(t, "map[string]interface{}", `{"a":1,"b":2.1,"c":{"A":10},"d":4}`, string(bytes)) 466 }) 467 }) 468 } 469 470 type mustErrTypeForDebug struct{} 471 472 func (mustErrTypeForDebug) MarshalJSON() ([]byte, error) { 473 panic("panic") 474 return nil, fmt.Errorf("panic") 475 } 476 477 func TestDebugMode(t *testing.T) { 478 defer func() { 479 if err := recover(); err == nil { 480 t.Fatal("expected error") 481 } 482 }() 483 var buf bytes.Buffer 484 json.MarshalWithOption(mustErrTypeForDebug{}, json.Debug(), json.DebugWith(&buf)) 485 } 486 487 func TestIssue116(t *testing.T) { 488 t.Run("first", func(t *testing.T) { 489 type Boo struct{ B string } 490 type Struct struct { 491 A int 492 Boo *Boo 493 } 494 type Embedded struct { 495 Struct 496 } 497 b, err := json.Marshal(Embedded{Struct: Struct{ 498 A: 1, 499 Boo: &Boo{B: "foo"}, 500 }}) 501 if err != nil { 502 t.Fatal(err) 503 } 504 expected := `{"A":1,"Boo":{"B":"foo"}}` 505 actual := string(b) 506 if actual != expected { 507 t.Fatalf("expected %s but got %s", expected, actual) 508 } 509 }) 510 t.Run("second", func(t *testing.T) { 511 type Boo struct{ B string } 512 type Struct struct { 513 A int 514 B *Boo 515 } 516 type Embedded struct { 517 Struct 518 } 519 b, err := json.Marshal(Embedded{Struct: Struct{ 520 A: 1, 521 B: &Boo{B: "foo"}, 522 }}) 523 if err != nil { 524 t.Fatal(err) 525 } 526 actual := string(b) 527 expected := `{"A":1,"B":{"B":"foo"}}` 528 if actual != expected { 529 t.Fatalf("expected %s but got %s", expected, actual) 530 } 531 }) 532 } 533 534 type marshalJSON struct{} 535 536 func (*marshalJSON) MarshalJSON() ([]byte, error) { 537 return []byte(`1`), nil 538 } 539 540 func Test_MarshalJSON(t *testing.T) { 541 t.Run("*struct", func(t *testing.T) { 542 bytes, err := json.Marshal(&marshalJSON{}) 543 assertErr(t, err) 544 assertEq(t, "MarshalJSON", "1", string(bytes)) 545 }) 546 t.Run("time", func(t *testing.T) { 547 bytes, err := json.Marshal(time.Time{}) 548 assertErr(t, err) 549 assertEq(t, "MarshalJSON", `"0001-01-01T00:00:00Z"`, string(bytes)) 550 }) 551 } 552 553 func Test_MarshalIndent(t *testing.T) { 554 prefix := "-" 555 indent := "\t" 556 t.Run("struct", func(t *testing.T) { 557 v := struct { 558 A int `json:"a"` 559 B uint `json:"b"` 560 C string `json:"c"` 561 D interface{} `json:"d"` 562 X int `json:"-"` // ignore field 563 a int `json:"aa"` // private field 564 }{ 565 A: -1, 566 B: 1, 567 C: "hello world", 568 D: struct { 569 E bool `json:"e"` 570 }{ 571 E: true, 572 }, 573 } 574 expected, err := stdjson.MarshalIndent(v, prefix, indent) 575 assertErr(t, err) 576 got, err := json.MarshalIndent(v, prefix, indent) 577 assertErr(t, err) 578 assertEq(t, "struct", string(expected), string(got)) 579 }) 580 t.Run("slice", func(t *testing.T) { 581 t.Run("[]int", func(t *testing.T) { 582 bytes, err := json.MarshalIndent([]int{1, 2, 3, 4}, prefix, indent) 583 assertErr(t, err) 584 result := "[\n-\t1,\n-\t2,\n-\t3,\n-\t4\n-]" 585 assertEq(t, "[]int", result, string(bytes)) 586 }) 587 t.Run("[]interface{}", func(t *testing.T) { 588 bytes, err := json.MarshalIndent([]interface{}{1, 2.1, "hello"}, prefix, indent) 589 assertErr(t, err) 590 result := "[\n-\t1,\n-\t2.1,\n-\t\"hello\"\n-]" 591 assertEq(t, "[]interface{}", result, string(bytes)) 592 }) 593 }) 594 595 t.Run("array", func(t *testing.T) { 596 bytes, err := json.MarshalIndent([4]int{1, 2, 3, 4}, prefix, indent) 597 assertErr(t, err) 598 result := "[\n-\t1,\n-\t2,\n-\t3,\n-\t4\n-]" 599 assertEq(t, "array", result, string(bytes)) 600 }) 601 t.Run("map", func(t *testing.T) { 602 t.Run("map[string]int", func(t *testing.T) { 603 bytes, err := json.MarshalIndent(map[string]int{ 604 "a": 1, 605 "b": 2, 606 "c": 3, 607 "d": 4, 608 }, prefix, indent) 609 assertErr(t, err) 610 result := "{\n-\t\"a\": 1,\n-\t\"b\": 2,\n-\t\"c\": 3,\n-\t\"d\": 4\n-}" 611 assertEq(t, "map", result, string(bytes)) 612 }) 613 t.Run("map[string]interface{}", func(t *testing.T) { 614 type T struct { 615 E int 616 F int 617 } 618 v := map[string]interface{}{ 619 "a": 1, 620 "b": 2.1, 621 "c": &T{ 622 E: 10, 623 F: 11, 624 }, 625 "d": 4, 626 } 627 bytes, err := json.MarshalIndent(v, prefix, indent) 628 assertErr(t, err) 629 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-}" 630 assertEq(t, "map[string]interface{}", result, string(bytes)) 631 }) 632 }) 633 } 634 635 type StringTag struct { 636 BoolStr bool `json:",string"` 637 IntStr int64 `json:",string"` 638 UintptrStr uintptr `json:",string"` 639 StrStr string `json:",string"` 640 NumberStr json.Number `json:",string"` 641 } 642 643 func TestRoundtripStringTag(t *testing.T) { 644 tests := []struct { 645 name string 646 in StringTag 647 want string // empty to just test that we roundtrip 648 }{ 649 { 650 name: "AllTypes", 651 in: StringTag{ 652 BoolStr: true, 653 IntStr: 42, 654 UintptrStr: 44, 655 StrStr: "xzbit", 656 NumberStr: "46", 657 }, 658 want: `{ 659 "BoolStr": "true", 660 "IntStr": "42", 661 "UintptrStr": "44", 662 "StrStr": "\"xzbit\"", 663 "NumberStr": "46" 664 }`, 665 }, 666 { 667 // See golang.org/issues/38173. 668 name: "StringDoubleEscapes", 669 in: StringTag{ 670 StrStr: "\b\f\n\r\t\"\\", 671 NumberStr: "0", // just to satisfy the roundtrip 672 }, 673 want: `{ 674 "BoolStr": "false", 675 "IntStr": "0", 676 "UintptrStr": "0", 677 "StrStr": "\"\\u0008\\u000c\\n\\r\\t\\\"\\\\\"", 678 "NumberStr": "0" 679 }`, 680 }, 681 } 682 for _, test := range tests { 683 t.Run(test.name, func(t *testing.T) { 684 // Indent with a tab prefix to make the multi-line string 685 // literals in the table nicer to read. 686 got, err := json.MarshalIndent(&test.in, "\t\t\t", "\t") 687 if err != nil { 688 t.Fatal(err) 689 } 690 if got := string(got); got != test.want { 691 t.Fatalf(" got: %s\nwant: %s\n", got, test.want) 692 } 693 694 // Verify that it round-trips. 695 var s2 StringTag 696 if err := json.Unmarshal(got, &s2); err != nil { 697 t.Fatalf("Decode: %v", err) 698 } 699 if !reflect.DeepEqual(test.in, s2) { 700 t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", test.in, string(got), s2) 701 } 702 }) 703 } 704 } 705 706 // byte slices are special even if they're renamed types. 707 type renamedByte byte 708 type renamedByteSlice []byte 709 type renamedRenamedByteSlice []renamedByte 710 711 func TestEncodeRenamedByteSlice(t *testing.T) { 712 s := renamedByteSlice("abc") 713 result, err := json.Marshal(s) 714 if err != nil { 715 t.Fatal(err) 716 } 717 expect := `"YWJj"` 718 if string(result) != expect { 719 t.Errorf(" got %s want %s", result, expect) 720 } 721 r := renamedRenamedByteSlice("abc") 722 result, err = json.Marshal(r) 723 if err != nil { 724 t.Fatal(err) 725 } 726 if string(result) != expect { 727 t.Errorf(" got %s want %s", result, expect) 728 } 729 } 730 731 func TestMarshalRawMessageValue(t *testing.T) { 732 type ( 733 T1 struct { 734 M json.RawMessage `json:",omitempty"` 735 } 736 T2 struct { 737 M *json.RawMessage `json:",omitempty"` 738 } 739 ) 740 741 var ( 742 rawNil = json.RawMessage(nil) 743 rawEmpty = json.RawMessage([]byte{}) 744 rawText = json.RawMessage([]byte(`"foo"`)) 745 ) 746 747 tests := []struct { 748 in interface{} 749 want string 750 ok bool 751 }{ 752 // Test with nil RawMessage. 753 {rawNil, "null", true}, 754 {&rawNil, "null", true}, 755 {[]interface{}{rawNil}, "[null]", true}, 756 {&[]interface{}{rawNil}, "[null]", true}, 757 {[]interface{}{&rawNil}, "[null]", true}, 758 {&[]interface{}{&rawNil}, "[null]", true}, 759 {struct{ M json.RawMessage }{rawNil}, `{"M":null}`, true}, 760 {&struct{ M json.RawMessage }{rawNil}, `{"M":null}`, true}, 761 {struct{ M *json.RawMessage }{&rawNil}, `{"M":null}`, true}, 762 {&struct{ M *json.RawMessage }{&rawNil}, `{"M":null}`, true}, 763 {map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, 764 {&map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, 765 {map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, 766 {&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, 767 {T1{rawNil}, "{}", true}, 768 {T2{&rawNil}, `{"M":null}`, true}, 769 {&T1{rawNil}, "{}", true}, 770 {&T2{&rawNil}, `{"M":null}`, true}, 771 772 // Test with empty, but non-nil, RawMessage. 773 {rawEmpty, "", false}, 774 {&rawEmpty, "", false}, 775 {[]interface{}{rawEmpty}, "", false}, 776 {&[]interface{}{rawEmpty}, "", false}, 777 {[]interface{}{&rawEmpty}, "", false}, 778 {&[]interface{}{&rawEmpty}, "", false}, 779 {struct{ X json.RawMessage }{rawEmpty}, "", false}, 780 {&struct{ X json.RawMessage }{rawEmpty}, "", false}, 781 {struct{ X *json.RawMessage }{&rawEmpty}, "", false}, 782 {&struct{ X *json.RawMessage }{&rawEmpty}, "", false}, 783 {map[string]interface{}{"nil": rawEmpty}, "", false}, 784 {&map[string]interface{}{"nil": rawEmpty}, "", false}, 785 {map[string]interface{}{"nil": &rawEmpty}, "", false}, 786 {&map[string]interface{}{"nil": &rawEmpty}, "", false}, 787 788 {T1{rawEmpty}, "{}", true}, 789 {T2{&rawEmpty}, "", false}, 790 {&T1{rawEmpty}, "{}", true}, 791 {&T2{&rawEmpty}, "", false}, 792 793 // Test with RawMessage with some text. 794 // 795 // The tests below marked with Issue6458 used to generate "ImZvbyI=" instead "foo". 796 // This behavior was intentionally changed in Go 1.8. 797 // See https://golang.org/issues/14493#issuecomment-255857318 798 {rawText, `"foo"`, true}, // Issue6458 799 {&rawText, `"foo"`, true}, 800 {[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 801 {&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 802 {[]interface{}{&rawText}, `["foo"]`, true}, 803 {&[]interface{}{&rawText}, `["foo"]`, true}, 804 {struct{ M json.RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458 805 {&struct{ M json.RawMessage }{rawText}, `{"M":"foo"}`, true}, 806 {struct{ M *json.RawMessage }{&rawText}, `{"M":"foo"}`, true}, 807 {&struct{ M *json.RawMessage }{&rawText}, `{"M":"foo"}`, true}, 808 {map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 809 {&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 810 {map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, 811 {&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, 812 {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458 813 {T2{&rawText}, `{"M":"foo"}`, true}, 814 {&T1{rawText}, `{"M":"foo"}`, true}, 815 {&T2{&rawText}, `{"M":"foo"}`, true}, 816 } 817 818 for i, tt := range tests { 819 b, err := json.Marshal(tt.in) 820 if ok := (err == nil); ok != tt.ok { 821 if err != nil { 822 t.Errorf("test %d, unexpected failure: %v", i, err) 823 } else { 824 t.Errorf("test %d, unexpected success", i) 825 } 826 } 827 if got := string(b); got != tt.want { 828 t.Errorf("test %d, Marshal(%#v) = %q, want %q", i, tt.in, got, tt.want) 829 } 830 } 831 } 832 833 type marshalerError struct{} 834 835 func (*marshalerError) MarshalJSON() ([]byte, error) { 836 return nil, errors.New("unexpected error") 837 } 838 839 func Test_MarshalerError(t *testing.T) { 840 var v marshalerError 841 _, err := json.Marshal(&v) 842 expect := `json: error calling MarshalJSON for type *json_test.marshalerError: unexpected error` 843 assertEq(t, "marshaler error", expect, fmt.Sprint(err)) 844 } 845 846 // Ref has Marshaler and Unmarshaler methods with pointer receiver. 847 type Ref int 848 849 func (*Ref) MarshalJSON() ([]byte, error) { 850 return []byte(`"ref"`), nil 851 } 852 853 func (r *Ref) UnmarshalJSON([]byte) error { 854 *r = 12 855 return nil 856 } 857 858 // Val has Marshaler methods with value receiver. 859 type Val int 860 861 func (Val) MarshalJSON() ([]byte, error) { 862 return []byte(`"val"`), nil 863 } 864 865 // RefText has Marshaler and Unmarshaler methods with pointer receiver. 866 type RefText int 867 868 func (*RefText) MarshalText() ([]byte, error) { 869 return []byte(`"ref"`), nil 870 } 871 872 func (r *RefText) UnmarshalText([]byte) error { 873 *r = 13 874 return nil 875 } 876 877 // ValText has Marshaler methods with value receiver. 878 type ValText int 879 880 func (ValText) MarshalText() ([]byte, error) { 881 return []byte(`"val"`), nil 882 } 883 884 func TestRefValMarshal(t *testing.T) { 885 var s = struct { 886 R0 Ref 887 R1 *Ref 888 R2 RefText 889 R3 *RefText 890 V0 Val 891 V1 *Val 892 V2 ValText 893 V3 *ValText 894 }{ 895 R0: 12, 896 R1: new(Ref), 897 R2: 14, 898 R3: new(RefText), 899 V0: 13, 900 V1: new(Val), 901 V2: 15, 902 V3: new(ValText), 903 } 904 const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}` 905 b, err := json.Marshal(&s) 906 if err != nil { 907 t.Fatalf("Marshal: %v", err) 908 } 909 if got := string(b); got != want { 910 t.Errorf("got %q, want %q", got, want) 911 } 912 } 913 914 // C implements Marshaler and returns unescaped JSON. 915 type C int 916 917 func (C) MarshalJSON() ([]byte, error) { 918 return []byte(`"<&>"`), nil 919 } 920 921 // CText implements Marshaler and returns unescaped text. 922 type CText int 923 924 func (CText) MarshalText() ([]byte, error) { 925 return []byte(`"<&>"`), nil 926 } 927 928 func TestMarshalerEscaping(t *testing.T) { 929 var c C 930 want := `"\u003c\u0026\u003e"` 931 b, err := json.Marshal(c) 932 if err != nil { 933 t.Fatalf("Marshal(c): %v", err) 934 } 935 if got := string(b); got != want { 936 t.Errorf("Marshal(c) = %#q, want %#q", got, want) 937 } 938 939 var ct CText 940 want = `"\"\u003c\u0026\u003e\""` 941 b, err = json.Marshal(ct) 942 if err != nil { 943 t.Fatalf("Marshal(ct): %v", err) 944 } 945 if got := string(b); got != want { 946 t.Errorf("Marshal(ct) = %#q, want %#q", got, want) 947 } 948 } 949 950 type marshalPanic struct{} 951 952 func (marshalPanic) MarshalJSON() ([]byte, error) { panic(0xdead) } 953 954 func TestMarshalPanic(t *testing.T) { 955 defer func() { 956 if got := recover(); !reflect.DeepEqual(got, 0xdead) { 957 t.Errorf("panic() = (%T)(%v), want 0xdead", got, got) 958 } 959 }() 960 json.Marshal(&marshalPanic{}) 961 t.Error("Marshal should have panicked") 962 } 963 964 func TestMarshalUncommonFieldNames(t *testing.T) { 965 v := struct { 966 A0, À, Aβ int 967 }{} 968 b, err := json.Marshal(v) 969 if err != nil { 970 t.Fatal("Marshal:", err) 971 } 972 want := `{"A0":0,"À":0,"Aβ":0}` 973 got := string(b) 974 if got != want { 975 t.Fatalf("Marshal: got %s want %s", got, want) 976 } 977 } 978 979 func TestMarshalerError(t *testing.T) { 980 s := "test variable" 981 st := reflect.TypeOf(s) 982 errText := "json: test error" 983 984 tests := []struct { 985 err *json.MarshalerError 986 want string 987 }{ 988 { 989 json.NewMarshalerError(st, fmt.Errorf(errText), ""), 990 "json: error calling MarshalJSON for type " + st.String() + ": " + errText, 991 }, 992 { 993 json.NewMarshalerError(st, fmt.Errorf(errText), "TestMarshalerError"), 994 "json: error calling TestMarshalerError for type " + st.String() + ": " + errText, 995 }, 996 } 997 998 for i, tt := range tests { 999 got := tt.err.Error() 1000 if got != tt.want { 1001 t.Errorf("MarshalerError test %d, got: %s, want: %s", i, got, tt.want) 1002 } 1003 } 1004 } 1005 1006 type unmarshalerText struct { 1007 A, B string 1008 } 1009 1010 // needed for re-marshaling tests 1011 func (u unmarshalerText) MarshalText() ([]byte, error) { 1012 return []byte(u.A + ":" + u.B), nil 1013 } 1014 1015 func (u *unmarshalerText) UnmarshalText(b []byte) error { 1016 pos := bytes.IndexByte(b, ':') 1017 if pos == -1 { 1018 return errors.New("missing separator") 1019 } 1020 u.A, u.B = string(b[:pos]), string(b[pos+1:]) 1021 return nil 1022 } 1023 1024 func TestTextMarshalerMapKeysAreSorted(t *testing.T) { 1025 b, err := json.Marshal(map[unmarshalerText]int{ 1026 {"x", "y"}: 1, 1027 {"y", "x"}: 2, 1028 {"a", "z"}: 3, 1029 {"z", "a"}: 4, 1030 }) 1031 if err != nil { 1032 t.Fatalf("Failed to Marshal text.Marshaler: %v", err) 1033 } 1034 const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}` 1035 if string(b) != want { 1036 t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) 1037 } 1038 } 1039 1040 // https://golang.org/issue/33675 1041 func TestNilMarshalerTextMapKey(t *testing.T) { 1042 v := map[*unmarshalerText]int{ 1043 (*unmarshalerText)(nil): 1, 1044 {"A", "B"}: 2, 1045 } 1046 b, err := json.Marshal(v) 1047 if err != nil { 1048 t.Fatalf("Failed to Marshal *text.Marshaler: %v", err) 1049 } 1050 const want = `{"":1,"A:B":2}` 1051 if string(b) != want { 1052 t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want) 1053 } 1054 } 1055 1056 var re = regexp.MustCompile 1057 1058 // syntactic checks on form of marshaled floating point numbers. 1059 var badFloatREs = []*regexp.Regexp{ 1060 re(`p`), // no binary exponential notation 1061 re(`^\+`), // no leading + sign 1062 re(`^-?0[^.]`), // no unnecessary leading zeros 1063 re(`^-?\.`), // leading zero required before decimal point 1064 re(`\.(e|$)`), // no trailing decimal 1065 re(`\.[0-9]+0(e|$)`), // no trailing zero in fraction 1066 re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa 1067 re(`e[0-9]`), // positive exponent must be signed 1068 //re(`e[+-]0`), // exponent must not have leading zeros 1069 re(`e-[1-6]$`), // not tiny enough for exponential notation 1070 re(`e+(.|1.|20)$`), // not big enough for exponential notation 1071 re(`^-?0\.0000000`), // too tiny, should use exponential notation 1072 re(`^-?[0-9]{22}`), // too big, should use exponential notation 1073 re(`[1-9][0-9]{16}[1-9]`), // too many significant digits in integer 1074 re(`[1-9][0-9.]{17}[1-9]`), // too many significant digits in decimal 1075 // below here for float32 only 1076 re(`[1-9][0-9]{8}[1-9]`), // too many significant digits in integer 1077 re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal 1078 } 1079 1080 func TestMarshalFloat(t *testing.T) { 1081 //t.Parallel() 1082 nfail := 0 1083 test := func(f float64, bits int) { 1084 vf := interface{}(f) 1085 if bits == 32 { 1086 f = float64(float32(f)) // round 1087 vf = float32(f) 1088 } 1089 bout, err := json.Marshal(vf) 1090 if err != nil { 1091 t.Errorf("Marshal(%T(%g)): %v", vf, vf, err) 1092 nfail++ 1093 return 1094 } 1095 out := string(bout) 1096 1097 // result must convert back to the same float 1098 g, err := strconv.ParseFloat(out, bits) 1099 if err != nil { 1100 t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err) 1101 nfail++ 1102 return 1103 } 1104 if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0 1105 t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf) 1106 nfail++ 1107 return 1108 } 1109 1110 bad := badFloatREs 1111 if bits == 64 { 1112 bad = bad[:len(bad)-2] 1113 } 1114 for _, re := range bad { 1115 if re.MatchString(out) { 1116 t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re) 1117 nfail++ 1118 return 1119 } 1120 } 1121 } 1122 1123 var ( 1124 bigger = math.Inf(+1) 1125 smaller = math.Inf(-1) 1126 ) 1127 1128 var digits = "1.2345678901234567890123" 1129 for i := len(digits); i >= 2; i-- { 1130 if testing.Short() && i < len(digits)-4 { 1131 break 1132 } 1133 for exp := -30; exp <= 30; exp++ { 1134 for _, sign := range "+-" { 1135 for bits := 32; bits <= 64; bits += 32 { 1136 s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp) 1137 f, err := strconv.ParseFloat(s, bits) 1138 if err != nil { 1139 log.Fatal(err) 1140 } 1141 next := math.Nextafter 1142 if bits == 32 { 1143 next = func(g, h float64) float64 { 1144 return float64(math.Nextafter32(float32(g), float32(h))) 1145 } 1146 } 1147 test(f, bits) 1148 test(next(f, bigger), bits) 1149 test(next(f, smaller), bits) 1150 if nfail > 50 { 1151 t.Fatalf("stopping test early") 1152 } 1153 } 1154 } 1155 } 1156 } 1157 test(0, 64) 1158 test(math.Copysign(0, -1), 64) 1159 test(0, 32) 1160 test(math.Copysign(0, -1), 32) 1161 } 1162 1163 var encodeStringTests = []struct { 1164 in string 1165 out string 1166 }{ 1167 {"\x00", `"\u0000"`}, 1168 {"\x01", `"\u0001"`}, 1169 {"\x02", `"\u0002"`}, 1170 {"\x03", `"\u0003"`}, 1171 {"\x04", `"\u0004"`}, 1172 {"\x05", `"\u0005"`}, 1173 {"\x06", `"\u0006"`}, 1174 {"\x07", `"\u0007"`}, 1175 {"\x08", `"\u0008"`}, 1176 {"\x09", `"\t"`}, 1177 {"\x0a", `"\n"`}, 1178 {"\x0b", `"\u000b"`}, 1179 {"\x0c", `"\u000c"`}, 1180 {"\x0d", `"\r"`}, 1181 {"\x0e", `"\u000e"`}, 1182 {"\x0f", `"\u000f"`}, 1183 {"\x10", `"\u0010"`}, 1184 {"\x11", `"\u0011"`}, 1185 {"\x12", `"\u0012"`}, 1186 {"\x13", `"\u0013"`}, 1187 {"\x14", `"\u0014"`}, 1188 {"\x15", `"\u0015"`}, 1189 {"\x16", `"\u0016"`}, 1190 {"\x17", `"\u0017"`}, 1191 {"\x18", `"\u0018"`}, 1192 {"\x19", `"\u0019"`}, 1193 {"\x1a", `"\u001a"`}, 1194 {"\x1b", `"\u001b"`}, 1195 {"\x1c", `"\u001c"`}, 1196 {"\x1d", `"\u001d"`}, 1197 {"\x1e", `"\u001e"`}, 1198 {"\x1f", `"\u001f"`}, 1199 } 1200 1201 func TestEncodeString(t *testing.T) { 1202 for _, tt := range encodeStringTests { 1203 b, err := json.Marshal(tt.in) 1204 if err != nil { 1205 t.Errorf("Marshal(%q): %v", tt.in, err) 1206 continue 1207 } 1208 out := string(b) 1209 if out != tt.out { 1210 t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out) 1211 } 1212 } 1213 } 1214 1215 type jsonbyte byte 1216 1217 func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) } 1218 1219 type textbyte byte 1220 1221 func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) } 1222 1223 type jsonint int 1224 1225 func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) } 1226 1227 type textint int 1228 1229 func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } 1230 1231 func tenc(format string, a ...interface{}) ([]byte, error) { 1232 var buf bytes.Buffer 1233 fmt.Fprintf(&buf, format, a...) 1234 return buf.Bytes(), nil 1235 } 1236 1237 // Issue 13783 1238 func TestEncodeBytekind(t *testing.T) { 1239 testdata := []struct { 1240 data interface{} 1241 want string 1242 }{ 1243 {byte(7), "7"}, 1244 {jsonbyte(7), `{"JB":7}`}, 1245 {textbyte(4), `"TB:4"`}, 1246 {jsonint(5), `{"JI":5}`}, 1247 {textint(1), `"TI:1"`}, 1248 {[]byte{0, 1}, `"AAE="`}, 1249 1250 {[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`}, 1251 {[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`}, 1252 {[]textbyte{2, 3}, `["TB:2","TB:3"]`}, 1253 1254 {[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`}, 1255 {[]textint{9, 3}, `["TI:9","TI:3"]`}, 1256 {[]int{9, 3}, `[9,3]`}, 1257 } 1258 for i, d := range testdata { 1259 js, err := json.Marshal(d.data) 1260 if err != nil { 1261 t.Error(err) 1262 continue 1263 } 1264 got, want := string(js), d.want 1265 if got != want { 1266 t.Errorf("%d: got %s, want %s", i, got, want) 1267 } 1268 } 1269 } 1270 1271 // golang.org/issue/8582 1272 func TestEncodePointerString(t *testing.T) { 1273 type stringPointer struct { 1274 N *int64 `json:"n,string"` 1275 } 1276 var n int64 = 42 1277 b, err := json.Marshal(stringPointer{N: &n}) 1278 if err != nil { 1279 t.Fatalf("Marshal: %v", err) 1280 } 1281 if got, want := string(b), `{"n":"42"}`; got != want { 1282 t.Errorf("Marshal = %s, want %s", got, want) 1283 } 1284 var back stringPointer 1285 err = json.Unmarshal(b, &back) 1286 if err != nil { 1287 t.Fatalf("Unmarshal: %v", err) 1288 } 1289 if back.N == nil { 1290 t.Fatalf("Unmarshaled nil N field") 1291 } 1292 if *back.N != 42 { 1293 t.Fatalf("*N = %d; want 42", *back.N) 1294 } 1295 } 1296 1297 type SamePointerNoCycle struct { 1298 Ptr1, Ptr2 *SamePointerNoCycle 1299 } 1300 1301 var samePointerNoCycle = &SamePointerNoCycle{} 1302 1303 type PointerCycle struct { 1304 Ptr *PointerCycle 1305 } 1306 1307 var pointerCycle = &PointerCycle{} 1308 1309 type PointerCycleIndirect struct { 1310 Ptrs []interface{} 1311 } 1312 1313 var pointerCycleIndirect = &PointerCycleIndirect{} 1314 1315 func init() { 1316 ptr := &SamePointerNoCycle{} 1317 samePointerNoCycle.Ptr1 = ptr 1318 samePointerNoCycle.Ptr2 = ptr 1319 1320 pointerCycle.Ptr = pointerCycle 1321 pointerCycleIndirect.Ptrs = []interface{}{pointerCycleIndirect} 1322 } 1323 1324 func TestSamePointerNoCycle(t *testing.T) { 1325 if _, err := json.Marshal(samePointerNoCycle); err != nil { 1326 t.Fatalf("unexpected error: %v", err) 1327 } 1328 } 1329 1330 var unsupportedValues = []interface{}{ 1331 math.NaN(), 1332 math.Inf(-1), 1333 math.Inf(1), 1334 pointerCycle, 1335 pointerCycleIndirect, 1336 } 1337 1338 func TestUnsupportedValues(t *testing.T) { 1339 for _, v := range unsupportedValues { 1340 if _, err := json.Marshal(v); err != nil { 1341 if _, ok := err.(*json.UnsupportedValueError); !ok { 1342 t.Errorf("for %v, got %T want UnsupportedValueError", v, err) 1343 } 1344 } else { 1345 t.Errorf("for %v, expected error", v) 1346 } 1347 } 1348 } 1349 1350 func TestIssue10281(t *testing.T) { 1351 type Foo struct { 1352 N json.Number 1353 } 1354 x := Foo{json.Number(`invalid`)} 1355 1356 b, err := json.Marshal(&x) 1357 if err == nil { 1358 t.Errorf("Marshal(&x) = %#q; want error", b) 1359 } 1360 } 1361 1362 func TestHTMLEscape(t *testing.T) { 1363 var b, want bytes.Buffer 1364 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` 1365 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) 1366 json.HTMLEscape(&b, []byte(m)) 1367 if !bytes.Equal(b.Bytes(), want.Bytes()) { 1368 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) 1369 } 1370 } 1371 1372 type BugA struct { 1373 S string 1374 } 1375 1376 type BugB struct { 1377 BugA 1378 S string 1379 } 1380 1381 type BugC struct { 1382 S string 1383 } 1384 1385 // Legal Go: We never use the repeated embedded field (S). 1386 type BugX struct { 1387 A int 1388 BugA 1389 BugB 1390 } 1391 1392 // golang.org/issue/16042. 1393 // Even if a nil interface value is passed in, as long as 1394 // it implements Marshaler, it should be marshaled. 1395 type nilJSONMarshaler string 1396 1397 func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) { 1398 if nm == nil { 1399 return json.Marshal("0zenil0") 1400 } 1401 return json.Marshal("zenil:" + string(*nm)) 1402 } 1403 1404 // golang.org/issue/34235. 1405 // Even if a nil interface value is passed in, as long as 1406 // it implements encoding.TextMarshaler, it should be marshaled. 1407 type nilTextMarshaler string 1408 1409 func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { 1410 if nm == nil { 1411 return []byte("0zenil0"), nil 1412 } 1413 return []byte("zenil:" + string(*nm)), nil 1414 } 1415 1416 // See golang.org/issue/16042 and golang.org/issue/34235. 1417 func TestNilMarshal(t *testing.T) { 1418 testCases := []struct { 1419 v interface{} 1420 want string 1421 }{ 1422 {v: nil, want: `null`}, 1423 {v: new(float64), want: `0`}, 1424 {v: []interface{}(nil), want: `null`}, 1425 {v: []string(nil), want: `null`}, 1426 {v: map[string]string(nil), want: `null`}, 1427 {v: []byte(nil), want: `null`}, 1428 {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, 1429 {v: struct{ M json.Marshaler }{}, want: `{"M":null}`}, 1430 {v: struct{ M json.Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1431 {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, 1432 {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, 1433 {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1434 {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, 1435 } 1436 1437 for i, tt := range testCases { 1438 out, err := json.Marshal(tt.v) 1439 if err != nil || string(out) != tt.want { 1440 t.Errorf("%d: Marshal(%#v) = %#q, %#v, want %#q, nil", i, tt.v, out, err, tt.want) 1441 continue 1442 } 1443 } 1444 } 1445 1446 // Issue 5245. 1447 func TestEmbeddedBug(t *testing.T) { 1448 v := BugB{ 1449 BugA{"A"}, 1450 "B", 1451 } 1452 b, err := json.Marshal(v) 1453 if err != nil { 1454 t.Fatal("Marshal:", err) 1455 } 1456 want := `{"S":"B"}` 1457 got := string(b) 1458 if got != want { 1459 t.Fatalf("Marshal: got %s want %s", got, want) 1460 } 1461 // Now check that the duplicate field, S, does not appear. 1462 x := BugX{ 1463 A: 23, 1464 } 1465 b, err = json.Marshal(x) 1466 if err != nil { 1467 t.Fatal("Marshal:", err) 1468 } 1469 want = `{"A":23}` 1470 got = string(b) 1471 if got != want { 1472 t.Fatalf("Marshal: got %s want %s", got, want) 1473 } 1474 } 1475 1476 type BugD struct { // Same as BugA after tagging. 1477 XXX string `json:"S"` 1478 } 1479 1480 // BugD's tagged S field should dominate BugA's. 1481 type BugY struct { 1482 BugA 1483 BugD 1484 } 1485 1486 // Test that a field with a tag dominates untagged fields. 1487 func TestTaggedFieldDominates(t *testing.T) { 1488 v := BugY{ 1489 BugA{"BugA"}, 1490 BugD{"BugD"}, 1491 } 1492 b, err := json.Marshal(v) 1493 if err != nil { 1494 t.Fatal("Marshal:", err) 1495 } 1496 want := `{"S":"BugD"}` 1497 got := string(b) 1498 if got != want { 1499 t.Fatalf("Marshal: got %s want %s", got, want) 1500 } 1501 } 1502 1503 // There are no tags here, so S should not appear. 1504 type BugZ struct { 1505 BugA 1506 BugC 1507 BugY // Contains a tagged S field through BugD; should not dominate. 1508 } 1509 1510 func TestDuplicatedFieldDisappears(t *testing.T) { 1511 v := BugZ{ 1512 BugA{"BugA"}, 1513 BugC{"BugC"}, 1514 BugY{ 1515 BugA{"nested BugA"}, 1516 BugD{"nested BugD"}, 1517 }, 1518 } 1519 b, err := json.Marshal(v) 1520 if err != nil { 1521 t.Fatal("Marshal:", err) 1522 } 1523 want := `{}` 1524 got := string(b) 1525 if got != want { 1526 t.Fatalf("Marshal: got %s want %s", got, want) 1527 } 1528 } 1529 1530 func TestAnonymousFields(t *testing.T) { 1531 tests := []struct { 1532 label string // Test name 1533 makeInput func() interface{} // Function to create input value 1534 want string // Expected JSON output 1535 }{{ 1536 // Both S1 and S2 have a field named X. From the perspective of S, 1537 // it is ambiguous which one X refers to. 1538 // This should not serialize either field. 1539 label: "AmbiguousField", 1540 makeInput: func() interface{} { 1541 type ( 1542 S1 struct{ x, X int } 1543 S2 struct{ x, X int } 1544 S struct { 1545 S1 1546 S2 1547 } 1548 ) 1549 return S{S1{1, 2}, S2{3, 4}} 1550 }, 1551 want: `{}`, 1552 }, { 1553 label: "DominantField", 1554 // Both S1 and S2 have a field named X, but since S has an X field as 1555 // well, it takes precedence over S1.X and S2.X. 1556 makeInput: func() interface{} { 1557 type ( 1558 S1 struct{ x, X int } 1559 S2 struct{ x, X int } 1560 S struct { 1561 S1 1562 S2 1563 x, X int 1564 } 1565 ) 1566 return S{S1{1, 2}, S2{3, 4}, 5, 6} 1567 }, 1568 want: `{"X":6}`, 1569 }, { 1570 // Unexported embedded field of non-struct type should not be serialized. 1571 label: "UnexportedEmbeddedInt", 1572 makeInput: func() interface{} { 1573 type ( 1574 myInt int 1575 S struct{ myInt } 1576 ) 1577 return S{5} 1578 }, 1579 want: `{}`, 1580 }, { 1581 // Exported embedded field of non-struct type should be serialized. 1582 label: "ExportedEmbeddedInt", 1583 makeInput: func() interface{} { 1584 type ( 1585 MyInt int 1586 S struct{ MyInt } 1587 ) 1588 return S{5} 1589 }, 1590 want: `{"MyInt":5}`, 1591 }, { 1592 // Unexported embedded field of pointer to non-struct type 1593 // should not be serialized. 1594 label: "UnexportedEmbeddedIntPointer", 1595 makeInput: func() interface{} { 1596 type ( 1597 myInt int 1598 S struct{ *myInt } 1599 ) 1600 s := S{new(myInt)} 1601 *s.myInt = 5 1602 return s 1603 }, 1604 want: `{}`, 1605 }, { 1606 // Exported embedded field of pointer to non-struct type 1607 // should be serialized. 1608 label: "ExportedEmbeddedIntPointer", 1609 makeInput: func() interface{} { 1610 type ( 1611 MyInt int 1612 S struct{ *MyInt } 1613 ) 1614 s := S{new(MyInt)} 1615 *s.MyInt = 5 1616 return s 1617 }, 1618 want: `{"MyInt":5}`, 1619 }, { 1620 // Exported fields of embedded structs should have their 1621 // exported fields be serialized regardless of whether the struct types 1622 // themselves are exported. 1623 label: "EmbeddedStruct", 1624 makeInput: func() interface{} { 1625 type ( 1626 s1 struct{ x, X int } 1627 S2 struct{ y, Y int } 1628 S struct { 1629 s1 1630 S2 1631 } 1632 ) 1633 return S{s1{1, 2}, S2{3, 4}} 1634 }, 1635 want: `{"X":2,"Y":4}`, 1636 }, { 1637 // Exported fields of pointers to embedded structs should have their 1638 // exported fields be serialized regardless of whether the struct types 1639 // themselves are exported. 1640 label: "EmbeddedStructPointer", 1641 makeInput: func() interface{} { 1642 type ( 1643 s1 struct{ x, X int } 1644 S2 struct{ y, Y int } 1645 S struct { 1646 *s1 1647 *S2 1648 } 1649 ) 1650 return S{&s1{1, 2}, &S2{3, 4}} 1651 }, 1652 want: `{"X":2,"Y":4}`, 1653 }, { 1654 // Exported fields on embedded unexported structs at multiple levels 1655 // of nesting should still be serialized. 1656 label: "NestedStructAndInts", 1657 makeInput: func() interface{} { 1658 type ( 1659 MyInt1 int 1660 MyInt2 int 1661 myInt int 1662 s2 struct { 1663 MyInt2 1664 myInt 1665 } 1666 s1 struct { 1667 MyInt1 1668 myInt 1669 s2 1670 } 1671 S struct { 1672 s1 1673 myInt 1674 } 1675 ) 1676 return S{s1{1, 2, s2{3, 4}}, 6} 1677 }, 1678 want: `{"MyInt1":1,"MyInt2":3}`, 1679 }, { 1680 // If an anonymous struct pointer field is nil, we should ignore 1681 // the embedded fields behind it. Not properly doing so may 1682 // result in the wrong output or reflect panics. 1683 label: "EmbeddedFieldBehindNilPointer", 1684 makeInput: func() interface{} { 1685 type ( 1686 S2 struct{ Field string } 1687 S struct{ *S2 } 1688 ) 1689 return S{} 1690 }, 1691 want: `{}`, 1692 }} 1693 1694 for i, tt := range tests { 1695 t.Run(tt.label, func(t *testing.T) { 1696 b, err := json.Marshal(tt.makeInput()) 1697 if err != nil { 1698 t.Fatalf("%d: Marshal() = %v, want nil error", i, err) 1699 } 1700 if string(b) != tt.want { 1701 t.Fatalf("%d: Marshal() = %q, want %q", i, b, tt.want) 1702 } 1703 }) 1704 } 1705 } 1706 1707 type Optionals struct { 1708 Sr string `json:"sr"` 1709 So string `json:"so,omitempty"` 1710 Sw string `json:"-"` 1711 1712 Ir int `json:"omitempty"` // actually named omitempty, not an option 1713 Io int `json:"io,omitempty"` 1714 1715 Slr []string `json:"slr,random"` 1716 Slo []string `json:"slo,omitempty"` 1717 1718 Mr map[string]interface{} `json:"mr"` 1719 Mo map[string]interface{} `json:",omitempty"` 1720 1721 Fr float64 `json:"fr"` 1722 Fo float64 `json:"fo,omitempty"` 1723 1724 Br bool `json:"br"` 1725 Bo bool `json:"bo,omitempty"` 1726 1727 Ur uint `json:"ur"` 1728 Uo uint `json:"uo,omitempty"` 1729 1730 Str struct{} `json:"str"` 1731 Sto struct{} `json:"sto,omitempty"` 1732 } 1733 1734 var optionalsExpected = `{ 1735 "sr": "", 1736 "omitempty": 0, 1737 "slr": null, 1738 "mr": {}, 1739 "fr": 0, 1740 "br": false, 1741 "ur": 0, 1742 "str": {}, 1743 "sto": {} 1744 }` 1745 1746 func TestOmitEmpty(t *testing.T) { 1747 var o Optionals 1748 o.Sw = "something" 1749 o.Mr = map[string]interface{}{} 1750 o.Mo = map[string]interface{}{} 1751 1752 got, err := json.MarshalIndent(&o, "", " ") 1753 if err != nil { 1754 t.Fatal(err) 1755 } 1756 if got := string(got); got != optionalsExpected { 1757 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) 1758 } 1759 } 1760 1761 type testNullStr string 1762 1763 func (v *testNullStr) MarshalJSON() ([]byte, error) { 1764 if *v == "" { 1765 return []byte("null"), nil 1766 } 1767 1768 return []byte(*v), nil 1769 } 1770 1771 func TestIssue147(t *testing.T) { 1772 type T struct { 1773 Field1 string `json:"field1"` 1774 Field2 testNullStr `json:"field2,omitempty"` 1775 } 1776 got, err := json.Marshal(T{ 1777 Field1: "a", 1778 Field2: "b", 1779 }) 1780 if err != nil { 1781 t.Fatal(err) 1782 } 1783 expect, _ := stdjson.Marshal(T{ 1784 Field1: "a", 1785 Field2: "b", 1786 }) 1787 if !bytes.Equal(expect, got) { 1788 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1789 } 1790 } 1791 1792 type testIssue144 struct { 1793 name string 1794 number int64 1795 } 1796 1797 func (v *testIssue144) MarshalJSON() ([]byte, error) { 1798 if v.name != "" { 1799 return json.Marshal(v.name) 1800 } 1801 return json.Marshal(v.number) 1802 } 1803 1804 func TestIssue144(t *testing.T) { 1805 type Embeded struct { 1806 Field *testIssue144 `json:"field,omitempty"` 1807 } 1808 type T struct { 1809 Embeded 1810 } 1811 { 1812 v := T{ 1813 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1814 } 1815 got, err := json.Marshal(v) 1816 if err != nil { 1817 t.Fatal(err) 1818 } 1819 expect, _ := stdjson.Marshal(v) 1820 if !bytes.Equal(expect, got) { 1821 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1822 } 1823 } 1824 { 1825 v := &T{ 1826 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1827 } 1828 got, err := json.Marshal(v) 1829 if err != nil { 1830 t.Fatal(err) 1831 } 1832 expect, _ := stdjson.Marshal(v) 1833 if !bytes.Equal(expect, got) { 1834 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1835 } 1836 } 1837 } 1838 1839 func TestIssue118(t *testing.T) { 1840 type data struct { 1841 Columns []string `json:"columns"` 1842 Rows1 [][]string `json:"rows1"` 1843 Rows2 [][]string `json:"rows2"` 1844 } 1845 v := data{Columns: []string{"1", "2", "3"}} 1846 got, err := json.MarshalIndent(v, "", " ") 1847 if err != nil { 1848 t.Fatal(err) 1849 } 1850 expect, _ := stdjson.MarshalIndent(v, "", " ") 1851 if !bytes.Equal(expect, got) { 1852 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1853 } 1854 } 1855 1856 func TestIssue104(t *testing.T) { 1857 type A struct { 1858 Field1 string 1859 Field2 int 1860 Field3 float64 1861 } 1862 type T struct { 1863 Field A 1864 } 1865 got, err := json.Marshal(T{}) 1866 if err != nil { 1867 t.Fatal(err) 1868 } 1869 expect, _ := stdjson.Marshal(T{}) 1870 if !bytes.Equal(expect, got) { 1871 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1872 } 1873 } 1874 1875 func TestIssue179(t *testing.T) { 1876 data := ` 1877 { 1878 "t": { 1879 "t1": false, 1880 "t2": 0, 1881 "t3": "", 1882 "t4": [], 1883 "t5": null, 1884 "t6": null 1885 } 1886 }` 1887 type T struct { 1888 X struct { 1889 T1 bool `json:"t1,omitempty"` 1890 T2 float64 `json:"t2,omitempty"` 1891 T3 string `json:"t3,omitempty"` 1892 T4 []string `json:"t4,omitempty"` 1893 T5 *struct{} `json:"t5,omitempty"` 1894 T6 interface{} `json:"t6,omitempty"` 1895 } `json:"x"` 1896 } 1897 var v T 1898 if err := stdjson.Unmarshal([]byte(data), &v); err != nil { 1899 t.Fatal(err) 1900 } 1901 var v2 T 1902 if err := json.Unmarshal([]byte(data), &v2); err != nil { 1903 t.Fatal(err) 1904 } 1905 if !reflect.DeepEqual(v, v2) { 1906 t.Fatalf("failed to decode: expected %v got %v", v, v2) 1907 } 1908 b1, err := stdjson.Marshal(v) 1909 if err != nil { 1910 t.Fatal(err) 1911 } 1912 b2, err := json.Marshal(v2) 1913 if err != nil { 1914 t.Fatal(err) 1915 } 1916 if !bytes.Equal(b1, b2) { 1917 t.Fatalf("failed to equal encoded result: expected %q but got %q", b1, b2) 1918 } 1919 } 1920 1921 func TestIssue180(t *testing.T) { 1922 v := struct { 1923 T struct { 1924 T1 bool `json:"t1"` 1925 T2 float64 `json:"t2"` 1926 T3 string `json:"t3"` 1927 T4 []string `json:"t4"` 1928 T5 *struct{} `json:"t5"` 1929 T6 interface{} `json:"t6"` 1930 T7 [][]string `json:"t7"` 1931 } `json:"t"` 1932 }{ 1933 T: struct { 1934 T1 bool `json:"t1"` 1935 T2 float64 `json:"t2"` 1936 T3 string `json:"t3"` 1937 T4 []string `json:"t4"` 1938 T5 *struct{} `json:"t5"` 1939 T6 interface{} `json:"t6"` 1940 T7 [][]string `json:"t7"` 1941 }{ 1942 T4: []string{}, 1943 T7: [][]string{ 1944 []string{""}, 1945 []string{"hello", "world"}, 1946 []string{}, 1947 }, 1948 }, 1949 } 1950 b1, err := stdjson.MarshalIndent(v, "", "\t") 1951 if err != nil { 1952 t.Fatal(err) 1953 } 1954 b2, err := json.MarshalIndent(v, "", "\t") 1955 if err != nil { 1956 t.Fatal(err) 1957 } 1958 if !bytes.Equal(b1, b2) { 1959 t.Fatalf("failed to equal encoded result: expected %s but got %s", string(b1), string(b2)) 1960 } 1961 } 1962 1963 func TestIssue235(t *testing.T) { 1964 type TaskMessage struct { 1965 Type string 1966 Payload map[string]interface{} 1967 UniqueKey string 1968 } 1969 msg := TaskMessage{ 1970 Payload: map[string]interface{}{ 1971 "sent_at": map[string]interface{}{ 1972 "Time": "0001-01-01T00:00:00Z", 1973 "Valid": false, 1974 }, 1975 }, 1976 } 1977 if _, err := json.Marshal(msg); err != nil { 1978 t.Fatal(err) 1979 } 1980 } 1981 1982 func TestEncodeMapKeyTypeInterface(t *testing.T) { 1983 if _, err := json.Marshal(map[interface{}]interface{}{"a": 1}); err == nil { 1984 t.Fatal("expected error") 1985 } 1986 } 1987 1988 type marshalContextKey struct{} 1989 1990 type marshalContextStructType struct{} 1991 1992 func (t *marshalContextStructType) MarshalJSON(ctx context.Context) ([]byte, error) { 1993 v := ctx.Value(marshalContextKey{}) 1994 s, ok := v.(string) 1995 if !ok { 1996 return nil, fmt.Errorf("failed to propagate parent context.Context") 1997 } 1998 if s != "hello" { 1999 return nil, fmt.Errorf("failed to propagate parent context.Context") 2000 } 2001 return []byte(`"success"`), nil 2002 } 2003 2004 func TestEncodeContextOption(t *testing.T) { 2005 t.Run("MarshalContext", func(t *testing.T) { 2006 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2007 b, err := json.MarshalContext(ctx, &marshalContextStructType{}) 2008 if err != nil { 2009 t.Fatal(err) 2010 } 2011 if string(b) != `"success"` { 2012 t.Fatal("failed to encode with MarshalerContext") 2013 } 2014 }) 2015 t.Run("EncodeContext", func(t *testing.T) { 2016 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2017 buf := bytes.NewBuffer([]byte{}) 2018 if err := json.NewEncoder(buf).EncodeContext(ctx, &marshalContextStructType{}); err != nil { 2019 t.Fatal(err) 2020 } 2021 if buf.String() != "\"success\"\n" { 2022 t.Fatal("failed to encode with EncodeContext") 2023 } 2024 }) 2025 } 2026 2027 func TestInterfaceWithPointer(t *testing.T) { 2028 var ( 2029 ivalue int = 10 2030 uvalue uint = 20 2031 svalue string = "value" 2032 bvalue bool = true 2033 fvalue float32 = 3.14 2034 nvalue json.Number = "1.23" 2035 structv = struct{ A int }{A: 10} 2036 slice = []int{1, 2, 3, 4} 2037 array = [4]int{1, 2, 3, 4} 2038 mapvalue = map[string]int{"a": 1} 2039 ) 2040 data := map[string]interface{}{ 2041 "ivalue": ivalue, 2042 "uvalue": uvalue, 2043 "svalue": svalue, 2044 "bvalue": bvalue, 2045 "fvalue": fvalue, 2046 "nvalue": nvalue, 2047 "struct": structv, 2048 "slice": slice, 2049 "array": array, 2050 "map": mapvalue, 2051 "pivalue": &ivalue, 2052 "puvalue": &uvalue, 2053 "psvalue": &svalue, 2054 "pbvalue": &bvalue, 2055 "pfvalue": &fvalue, 2056 "pnvalue": &nvalue, 2057 "pstruct": &structv, 2058 "pslice": &slice, 2059 "parray": &array, 2060 "pmap": &mapvalue, 2061 } 2062 expected, err := stdjson.Marshal(data) 2063 if err != nil { 2064 t.Fatal(err) 2065 } 2066 actual, err := json.Marshal(data) 2067 if err != nil { 2068 t.Fatal(err) 2069 } 2070 assertEq(t, "interface{}", string(expected), string(actual)) 2071 } 2072 2073 func TestIssue263(t *testing.T) { 2074 type Foo struct { 2075 A []string `json:"a"` 2076 B int `json:"b"` 2077 } 2078 2079 type MyStruct struct { 2080 Foo *Foo `json:"foo,omitempty"` 2081 } 2082 2083 s := MyStruct{ 2084 Foo: &Foo{ 2085 A: []string{"ls -lah"}, 2086 B: 0, 2087 }, 2088 } 2089 expected, err := stdjson.Marshal(s) 2090 if err != nil { 2091 t.Fatal(err) 2092 } 2093 actual, err := json.Marshal(s) 2094 if err != nil { 2095 t.Fatal(err) 2096 } 2097 if !bytes.Equal(expected, actual) { 2098 t.Fatalf("expected:[%s] but got:[%s]", string(expected), string(actual)) 2099 } 2100 } 2101 2102 func TestEmbeddedNotFirstField(t *testing.T) { 2103 type Embedded struct { 2104 Has bool `json:"has"` 2105 } 2106 type T struct { 2107 X int `json:"is"` 2108 Embedded `json:"child"` 2109 } 2110 p := T{X: 10, Embedded: Embedded{Has: true}} 2111 expected, err := stdjson.Marshal(&p) 2112 if err != nil { 2113 t.Fatal(err) 2114 } 2115 got, err := json.Marshal(&p) 2116 if err != nil { 2117 t.Fatal(err) 2118 } 2119 if !bytes.Equal(expected, got) { 2120 t.Fatalf("failed to encode embedded structure. expected = %q but got %q", expected, got) 2121 } 2122 } 2123 2124 type implementedMethodIface interface { 2125 M() 2126 } 2127 2128 type implementedIfaceType struct { 2129 A int 2130 B string 2131 } 2132 2133 func (implementedIfaceType) M() {} 2134 2135 func TestImplementedMethodInterfaceType(t *testing.T) { 2136 data := []implementedIfaceType{implementedIfaceType{}} 2137 expected, err := stdjson.Marshal(data) 2138 if err != nil { 2139 t.Fatal(err) 2140 } 2141 got, err := json.Marshal(data) 2142 if err != nil { 2143 t.Fatal(err) 2144 } 2145 if !bytes.Equal(expected, got) { 2146 t.Fatalf("failed to encode implemented method interface type. expected:[%q] but got:[%q]", expected, got) 2147 } 2148 } 2149 2150 func TestEmptyStructInterface(t *testing.T) { 2151 expected, err := stdjson.Marshal([]interface{}{struct{}{}}) 2152 if err != nil { 2153 t.Fatal(err) 2154 } 2155 got, err := json.Marshal([]interface{}{struct{}{}}) 2156 if err != nil { 2157 t.Fatal(err) 2158 } 2159 if !bytes.Equal(expected, got) { 2160 t.Fatalf("failed to encode empty struct interface. expected:[%q] but got:[%q]", expected, got) 2161 } 2162 } 2163 2164 func TestIssue290(t *testing.T) { 2165 type Issue290 interface { 2166 A() 2167 } 2168 var a struct { 2169 A Issue290 2170 } 2171 expected, err := stdjson.Marshal(a) 2172 if err != nil { 2173 t.Fatal(err) 2174 } 2175 got, err := json.Marshal(a) 2176 if err != nil { 2177 t.Fatal(err) 2178 } 2179 if !bytes.Equal(expected, got) { 2180 t.Fatalf("failed to encode non empty interface. expected = %q but got %q", expected, got) 2181 } 2182 } 2183 2184 func TestIssue299(t *testing.T) { 2185 t.Run("conflict second field", func(t *testing.T) { 2186 type Embedded struct { 2187 ID string `json:"id"` 2188 Name map[string]string `json:"name"` 2189 } 2190 type Container struct { 2191 Embedded 2192 Name string `json:"name"` 2193 } 2194 c := &Container{ 2195 Embedded: Embedded{ 2196 ID: "1", 2197 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2198 }, 2199 Name: "Hi", 2200 } 2201 expected, _ := stdjson.Marshal(c) 2202 got, err := json.Marshal(c) 2203 if err != nil { 2204 t.Fatal(err) 2205 } 2206 if !bytes.Equal(expected, got) { 2207 t.Fatalf("expected %q but got %q", expected, got) 2208 } 2209 }) 2210 t.Run("conflict map field", func(t *testing.T) { 2211 type Embedded struct { 2212 Name map[string]string `json:"name"` 2213 } 2214 type Container struct { 2215 Embedded 2216 Name string `json:"name"` 2217 } 2218 c := &Container{ 2219 Embedded: Embedded{ 2220 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2221 }, 2222 Name: "Hi", 2223 } 2224 expected, _ := stdjson.Marshal(c) 2225 got, err := json.Marshal(c) 2226 if err != nil { 2227 t.Fatal(err) 2228 } 2229 if !bytes.Equal(expected, got) { 2230 t.Fatalf("expected %q but got %q", expected, got) 2231 } 2232 }) 2233 t.Run("conflict slice field", func(t *testing.T) { 2234 type Embedded struct { 2235 Name []string `json:"name"` 2236 } 2237 type Container struct { 2238 Embedded 2239 Name string `json:"name"` 2240 } 2241 c := &Container{ 2242 Embedded: Embedded{ 2243 Name: []string{"Hello"}, 2244 }, 2245 Name: "Hi", 2246 } 2247 expected, _ := stdjson.Marshal(c) 2248 got, err := json.Marshal(c) 2249 if err != nil { 2250 t.Fatal(err) 2251 } 2252 if !bytes.Equal(expected, got) { 2253 t.Fatalf("expected %q but got %q", expected, got) 2254 } 2255 }) 2256 } 2257 2258 func TestRecursivePtrHead(t *testing.T) { 2259 type User struct { 2260 Account *string `json:"account"` 2261 Password *string `json:"password"` 2262 Nickname *string `json:"nickname"` 2263 Address *string `json:"address,omitempty"` 2264 Friends []*User `json:"friends,omitempty"` 2265 } 2266 user1Account, user1Password, user1Nickname := "abcdef", "123456", "user1" 2267 user1 := &User{ 2268 Account: &user1Account, 2269 Password: &user1Password, 2270 Nickname: &user1Nickname, 2271 Address: nil, 2272 } 2273 user2Account, user2Password, user2Nickname := "ghijkl", "123456", "user2" 2274 user2 := &User{ 2275 Account: &user2Account, 2276 Password: &user2Password, 2277 Nickname: &user2Nickname, 2278 Address: nil, 2279 } 2280 user1.Friends = []*User{user2} 2281 expected, err := stdjson.Marshal(user1) 2282 if err != nil { 2283 t.Fatal(err) 2284 } 2285 got, err := json.Marshal(user1) 2286 if err != nil { 2287 t.Fatal(err) 2288 } 2289 if !bytes.Equal(expected, got) { 2290 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2291 } 2292 } 2293 2294 func TestMarshalIndent(t *testing.T) { 2295 v := map[string]map[string]interface{}{ 2296 "a": { 2297 "b": "1", 2298 "c": map[string]interface{}{ 2299 "d": "1", 2300 }, 2301 }, 2302 } 2303 expected, err := stdjson.MarshalIndent(v, "", " ") 2304 if err != nil { 2305 t.Fatal(err) 2306 } 2307 got, err := json.MarshalIndent(v, "", " ") 2308 if err != nil { 2309 t.Fatal(err) 2310 } 2311 if !bytes.Equal(expected, got) { 2312 t.Fatalf("expected: %q but got %q", expected, got) 2313 } 2314 } 2315 2316 type issue318Embedded struct { 2317 _ [64]byte 2318 } 2319 2320 type issue318 struct { 2321 issue318Embedded `json:"-"` 2322 ID issue318MarshalText `json:"id,omitempty"` 2323 } 2324 2325 type issue318MarshalText struct { 2326 ID string 2327 } 2328 2329 func (i issue318MarshalText) MarshalText() ([]byte, error) { 2330 return []byte(i.ID), nil 2331 } 2332 2333 func TestIssue318(t *testing.T) { 2334 v := issue318{ 2335 ID: issue318MarshalText{ID: "1"}, 2336 } 2337 b, err := json.Marshal(v) 2338 if err != nil { 2339 t.Fatal(err) 2340 } 2341 expected := `{"id":"1"}` 2342 if string(b) != expected { 2343 t.Fatalf("failed to encode. expected %s but got %s", expected, string(b)) 2344 } 2345 } 2346 2347 type emptyStringMarshaler struct { 2348 Value stringMarshaler `json:"value,omitempty"` 2349 } 2350 2351 type stringMarshaler string 2352 2353 func (s stringMarshaler) MarshalJSON() ([]byte, error) { 2354 return []byte(`"` + s + `"`), nil 2355 } 2356 2357 func TestEmptyStringMarshaler(t *testing.T) { 2358 value := emptyStringMarshaler{} 2359 expected, err := stdjson.Marshal(value) 2360 assertErr(t, err) 2361 got, err := json.Marshal(value) 2362 assertErr(t, err) 2363 assertEq(t, "struct", string(expected), string(got)) 2364 } 2365 2366 func TestIssue324(t *testing.T) { 2367 type T struct { 2368 FieldA *string `json:"fieldA,omitempty"` 2369 FieldB *string `json:"fieldB,omitempty"` 2370 FieldC *bool `json:"fieldC"` 2371 FieldD []string `json:"fieldD,omitempty"` 2372 } 2373 v := &struct { 2374 Code string `json:"code"` 2375 *T 2376 }{ 2377 T: &T{}, 2378 } 2379 var sv = "Test Field" 2380 v.Code = "Test" 2381 v.T.FieldB = &sv 2382 expected, err := stdjson.Marshal(v) 2383 if err != nil { 2384 t.Fatal(err) 2385 } 2386 got, err := json.Marshal(v) 2387 if err != nil { 2388 t.Fatal(err) 2389 } 2390 if !bytes.Equal(expected, got) { 2391 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2392 } 2393 } 2394 2395 func TestIssue339(t *testing.T) { 2396 type T1 struct { 2397 *big.Int 2398 } 2399 type T2 struct { 2400 T1 T1 `json:"T1"` 2401 } 2402 v := T2{T1{Int: big.NewInt(10000)}} 2403 b, err := json.Marshal(&v) 2404 assertErr(t, err) 2405 got := string(b) 2406 expected := `{"T1":10000}` 2407 if got != expected { 2408 t.Errorf("unexpected result: %v != %v", got, expected) 2409 } 2410 } 2411 2412 func TestIssue376(t *testing.T) { 2413 type Container struct { 2414 V interface{} `json:"value"` 2415 } 2416 type MapOnly struct { 2417 Map map[string]int64 `json:"map"` 2418 } 2419 b, err := json.Marshal(Container{MapOnly{}}) 2420 if err != nil { 2421 t.Fatal(err) 2422 } 2423 got := string(b) 2424 expected := `{"value":{"map":null}}` 2425 if got != expected { 2426 t.Errorf("unexpected result: %v != %v", got, expected) 2427 } 2428 } 2429 2430 type Issue370 struct { 2431 String string 2432 Valid bool 2433 } 2434 2435 func (i *Issue370) MarshalJSON() ([]byte, error) { 2436 if !i.Valid { 2437 return json.Marshal(nil) 2438 } 2439 return json.Marshal(i.String) 2440 } 2441 2442 func TestIssue370(t *testing.T) { 2443 v := []struct { 2444 V Issue370 2445 }{ 2446 {V: Issue370{String: "test", Valid: true}}, 2447 } 2448 b, err := json.Marshal(v) 2449 if err != nil { 2450 t.Fatal(err) 2451 } 2452 got := string(b) 2453 expected := `[{"V":"test"}]` 2454 if got != expected { 2455 t.Errorf("unexpected result: %v != %v", got, expected) 2456 } 2457 } 2458 2459 func TestIssue374(t *testing.T) { 2460 r := io.MultiReader(strings.NewReader(strings.Repeat(" ", 505)+`"\u`), strings.NewReader(`0000"`)) 2461 var v interface{} 2462 if err := json.NewDecoder(r).Decode(&v); err != nil { 2463 t.Fatal(err) 2464 } 2465 got := v.(string) 2466 expected := "\u0000" 2467 if got != expected { 2468 t.Errorf("unexpected result: %q != %q", got, expected) 2469 } 2470 } 2471 2472 func TestIssue381(t *testing.T) { 2473 var v struct { 2474 Field0 bool 2475 Field1 bool 2476 Field2 bool 2477 Field3 bool 2478 Field4 bool 2479 Field5 bool 2480 Field6 bool 2481 Field7 bool 2482 Field8 bool 2483 Field9 bool 2484 Field10 bool 2485 Field11 bool 2486 Field12 bool 2487 Field13 bool 2488 Field14 bool 2489 Field15 bool 2490 Field16 bool 2491 Field17 bool 2492 Field18 bool 2493 Field19 bool 2494 Field20 bool 2495 Field21 bool 2496 Field22 bool 2497 Field23 bool 2498 Field24 bool 2499 Field25 bool 2500 Field26 bool 2501 Field27 bool 2502 Field28 bool 2503 Field29 bool 2504 Field30 bool 2505 Field31 bool 2506 Field32 bool 2507 Field33 bool 2508 Field34 bool 2509 Field35 bool 2510 Field36 bool 2511 Field37 bool 2512 Field38 bool 2513 Field39 bool 2514 Field40 bool 2515 Field41 bool 2516 Field42 bool 2517 Field43 bool 2518 Field44 bool 2519 Field45 bool 2520 Field46 bool 2521 Field47 bool 2522 Field48 bool 2523 Field49 bool 2524 Field50 bool 2525 Field51 bool 2526 Field52 bool 2527 Field53 bool 2528 Field54 bool 2529 Field55 bool 2530 Field56 bool 2531 Field57 bool 2532 Field58 bool 2533 Field59 bool 2534 Field60 bool 2535 Field61 bool 2536 Field62 bool 2537 Field63 bool 2538 Field64 bool 2539 Field65 bool 2540 Field66 bool 2541 Field67 bool 2542 Field68 bool 2543 Field69 bool 2544 Field70 bool 2545 Field71 bool 2546 Field72 bool 2547 Field73 bool 2548 Field74 bool 2549 Field75 bool 2550 Field76 bool 2551 Field77 bool 2552 Field78 bool 2553 Field79 bool 2554 Field80 bool 2555 Field81 bool 2556 Field82 bool 2557 Field83 bool 2558 Field84 bool 2559 Field85 bool 2560 Field86 bool 2561 Field87 bool 2562 Field88 bool 2563 Field89 bool 2564 Field90 bool 2565 Field91 bool 2566 Field92 bool 2567 Field93 bool 2568 Field94 bool 2569 Field95 bool 2570 Field96 bool 2571 Field97 bool 2572 Field98 bool 2573 Field99 bool 2574 } 2575 2576 // test encoder cache issue, not related to encoder 2577 b, err := json.Marshal(v) 2578 if err != nil { 2579 t.Errorf("failed to marshal %s", err.Error()) 2580 t.FailNow() 2581 } 2582 2583 std, err := stdjson.Marshal(v) 2584 if err != nil { 2585 t.Errorf("failed to marshal with encoding/json %s", err.Error()) 2586 t.FailNow() 2587 } 2588 2589 if !bytes.Equal(std, b) { 2590 t.Errorf("encoding result not equal to encoding/json") 2591 t.FailNow() 2592 } 2593 } 2594 2595 func TestIssue386(t *testing.T) { 2596 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)"}` 2597 var a struct { 2598 Date *string `json:"date"` 2599 Platform *string `json:"platform"` 2600 Summary string `json:"summary"` 2601 Name string `json:"name"` 2602 } 2603 err := json.NewDecoder(strings.NewReader(raw)).Decode(&a) 2604 if err != nil { 2605 t.Error(err) 2606 } 2607 }