github.com/goccy/go-json@v0.10.3-0.20240509105655-5e2ae3f23c1d/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/goccy/go-json" 22 ) 23 24 type recursiveT struct { 25 A *recursiveT `json:"a,omitempty"` 26 B *recursiveU `json:"b,omitempty"` 27 C *recursiveU `json:"c,omitempty"` 28 D string `json:"d,omitempty"` 29 } 30 31 type recursiveU struct { 32 T *recursiveT `json:"t,omitempty"` 33 } 34 35 func Test_Marshal(t *testing.T) { 36 t.Run("int", func(t *testing.T) { 37 bytes, err := json.Marshal(-10) 38 assertErr(t, err) 39 assertEq(t, "int", `-10`, string(bytes)) 40 }) 41 t.Run("int8", func(t *testing.T) { 42 bytes, err := json.Marshal(int8(-11)) 43 assertErr(t, err) 44 assertEq(t, "int8", `-11`, string(bytes)) 45 }) 46 t.Run("int16", func(t *testing.T) { 47 bytes, err := json.Marshal(int16(-12)) 48 assertErr(t, err) 49 assertEq(t, "int16", `-12`, string(bytes)) 50 }) 51 t.Run("int32", func(t *testing.T) { 52 bytes, err := json.Marshal(int32(-13)) 53 assertErr(t, err) 54 assertEq(t, "int32", `-13`, string(bytes)) 55 }) 56 t.Run("int64", func(t *testing.T) { 57 bytes, err := json.Marshal(int64(-14)) 58 assertErr(t, err) 59 assertEq(t, "int64", `-14`, string(bytes)) 60 }) 61 t.Run("uint", func(t *testing.T) { 62 bytes, err := json.Marshal(uint(10)) 63 assertErr(t, err) 64 assertEq(t, "uint", `10`, string(bytes)) 65 }) 66 t.Run("uint8", func(t *testing.T) { 67 bytes, err := json.Marshal(uint8(11)) 68 assertErr(t, err) 69 assertEq(t, "uint8", `11`, string(bytes)) 70 }) 71 t.Run("uint16", func(t *testing.T) { 72 bytes, err := json.Marshal(uint16(12)) 73 assertErr(t, err) 74 assertEq(t, "uint16", `12`, string(bytes)) 75 }) 76 t.Run("uint32", func(t *testing.T) { 77 bytes, err := json.Marshal(uint32(13)) 78 assertErr(t, err) 79 assertEq(t, "uint32", `13`, string(bytes)) 80 }) 81 t.Run("uint64", func(t *testing.T) { 82 bytes, err := json.Marshal(uint64(14)) 83 assertErr(t, err) 84 assertEq(t, "uint64", `14`, string(bytes)) 85 }) 86 t.Run("float32", func(t *testing.T) { 87 bytes, err := json.Marshal(float32(3.14)) 88 assertErr(t, err) 89 assertEq(t, "float32", `3.14`, string(bytes)) 90 }) 91 t.Run("float64", func(t *testing.T) { 92 bytes, err := json.Marshal(float64(3.14)) 93 assertErr(t, err) 94 assertEq(t, "float64", `3.14`, string(bytes)) 95 }) 96 t.Run("bool", func(t *testing.T) { 97 bytes, err := json.Marshal(true) 98 assertErr(t, err) 99 assertEq(t, "bool", `true`, string(bytes)) 100 }) 101 t.Run("string", func(t *testing.T) { 102 bytes, err := json.Marshal("hello world") 103 assertErr(t, err) 104 assertEq(t, "string", `"hello world"`, string(bytes)) 105 }) 106 t.Run("struct", func(t *testing.T) { 107 bytes, err := json.Marshal(struct { 108 A int `json:"a"` 109 B uint `json:"b"` 110 C string `json:"c"` 111 D int `json:"-"` // ignore field 112 a int `json:"aa"` // private field 113 }{ 114 A: -1, 115 B: 1, 116 C: "hello world", 117 }) 118 assertErr(t, err) 119 assertEq(t, "struct", `{"a":-1,"b":1,"c":"hello world"}`, string(bytes)) 120 t.Run("null", func(t *testing.T) { 121 type T struct { 122 A *struct{} `json:"a"` 123 } 124 var v T 125 bytes, err := json.Marshal(&v) 126 assertErr(t, err) 127 assertEq(t, "struct", `{"a":null}`, string(bytes)) 128 }) 129 t.Run("recursive", func(t *testing.T) { 130 bytes, err := json.Marshal(recursiveT{ 131 A: &recursiveT{ 132 B: &recursiveU{ 133 T: &recursiveT{ 134 D: "hello", 135 }, 136 }, 137 C: &recursiveU{ 138 T: &recursiveT{ 139 D: "world", 140 }, 141 }, 142 }, 143 }) 144 assertErr(t, err) 145 assertEq(t, "recursive", `{"a":{"b":{"t":{"d":"hello"}},"c":{"t":{"d":"world"}}}}`, string(bytes)) 146 }) 147 t.Run("embedded", func(t *testing.T) { 148 type T struct { 149 A string `json:"a"` 150 } 151 type U struct { 152 *T 153 B string `json:"b"` 154 } 155 type T2 struct { 156 A string `json:"a,omitempty"` 157 } 158 type U2 struct { 159 *T2 160 B string `json:"b,omitempty"` 161 } 162 t.Run("exists field", func(t *testing.T) { 163 bytes, err := json.Marshal(&U{ 164 T: &T{ 165 A: "aaa", 166 }, 167 B: "bbb", 168 }) 169 assertErr(t, err) 170 assertEq(t, "embedded", `{"a":"aaa","b":"bbb"}`, string(bytes)) 171 t.Run("omitempty", func(t *testing.T) { 172 bytes, err := json.Marshal(&U2{ 173 T2: &T2{ 174 A: "aaa", 175 }, 176 B: "bbb", 177 }) 178 assertErr(t, err) 179 assertEq(t, "embedded", `{"a":"aaa","b":"bbb"}`, string(bytes)) 180 }) 181 }) 182 t.Run("none field", func(t *testing.T) { 183 bytes, err := json.Marshal(&U{ 184 B: "bbb", 185 }) 186 assertErr(t, err) 187 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes)) 188 t.Run("omitempty", func(t *testing.T) { 189 bytes, err := json.Marshal(&U2{ 190 B: "bbb", 191 }) 192 assertErr(t, err) 193 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes)) 194 }) 195 }) 196 }) 197 198 t.Run("embedded with tag", func(t *testing.T) { 199 type T struct { 200 A string `json:"a"` 201 } 202 type U struct { 203 *T `json:"t"` 204 B string `json:"b"` 205 } 206 type T2 struct { 207 A string `json:"a,omitempty"` 208 } 209 type U2 struct { 210 *T2 `json:"t,omitempty"` 211 B string `json:"b,omitempty"` 212 } 213 t.Run("exists field", func(t *testing.T) { 214 bytes, err := json.Marshal(&U{ 215 T: &T{ 216 A: "aaa", 217 }, 218 B: "bbb", 219 }) 220 assertErr(t, err) 221 assertEq(t, "embedded", `{"t":{"a":"aaa"},"b":"bbb"}`, string(bytes)) 222 t.Run("omitempty", func(t *testing.T) { 223 bytes, err := json.Marshal(&U2{ 224 T2: &T2{ 225 A: "aaa", 226 }, 227 B: "bbb", 228 }) 229 assertErr(t, err) 230 assertEq(t, "embedded", `{"t":{"a":"aaa"},"b":"bbb"}`, string(bytes)) 231 }) 232 }) 233 234 t.Run("none field", func(t *testing.T) { 235 bytes, err := json.Marshal(&U{ 236 B: "bbb", 237 }) 238 assertErr(t, err) 239 assertEq(t, "embedded", `{"t":null,"b":"bbb"}`, string(bytes)) 240 t.Run("omitempty", func(t *testing.T) { 241 bytes, err := json.Marshal(&U2{ 242 B: "bbb", 243 }) 244 assertErr(t, err) 245 assertEq(t, "embedded", `{"b":"bbb"}`, string(bytes)) 246 }) 247 }) 248 }) 249 250 t.Run("omitempty", func(t *testing.T) { 251 type T struct { 252 A int `json:",omitempty"` 253 B int8 `json:",omitempty"` 254 C int16 `json:",omitempty"` 255 D int32 `json:",omitempty"` 256 E int64 `json:",omitempty"` 257 F uint `json:",omitempty"` 258 G uint8 `json:",omitempty"` 259 H uint16 `json:",omitempty"` 260 I uint32 `json:",omitempty"` 261 J uint64 `json:",omitempty"` 262 K float32 `json:",omitempty"` 263 L float64 `json:",omitempty"` 264 O string `json:",omitempty"` 265 P bool `json:",omitempty"` 266 Q []int `json:",omitempty"` 267 R map[string]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 data := map[unmarshalerText]int{ 1026 {"x", "y"}: 1, 1027 {"y", "x"}: 2, 1028 {"a", "z"}: 3, 1029 {"z", "a"}: 4, 1030 } 1031 b, err := json.Marshal(data) 1032 if err != nil { 1033 t.Fatalf("Failed to Marshal text.Marshaler: %v", err) 1034 } 1035 const want = `{"a:z":3,"x:y":1,"y:x":2,"z:a":4}` 1036 if string(b) != want { 1037 t.Errorf("Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) 1038 } 1039 1040 b, err = stdjson.Marshal(data) 1041 if err != nil { 1042 t.Fatalf("Failed to std Marshal text.Marshaler: %v", err) 1043 } 1044 if string(b) != want { 1045 t.Errorf("std Marshal map with text.Marshaler keys: got %#q, want %#q", b, want) 1046 } 1047 } 1048 1049 // https://golang.org/issue/33675 1050 func TestNilMarshalerTextMapKey(t *testing.T) { 1051 v := map[*unmarshalerText]int{ 1052 (*unmarshalerText)(nil): 1, 1053 {"A", "B"}: 2, 1054 } 1055 b, err := json.Marshal(v) 1056 if err != nil { 1057 t.Fatalf("Failed to Marshal *text.Marshaler: %v", err) 1058 } 1059 const want = `{"":1,"A:B":2}` 1060 if string(b) != want { 1061 t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want) 1062 } 1063 } 1064 1065 var re = regexp.MustCompile 1066 1067 // syntactic checks on form of marshaled floating point numbers. 1068 var badFloatREs = []*regexp.Regexp{ 1069 re(`p`), // no binary exponential notation 1070 re(`^\+`), // no leading + sign 1071 re(`^-?0[^.]`), // no unnecessary leading zeros 1072 re(`^-?\.`), // leading zero required before decimal point 1073 re(`\.(e|$)`), // no trailing decimal 1074 re(`\.[0-9]+0(e|$)`), // no trailing zero in fraction 1075 re(`^-?(0|[0-9]{2,})\..*e`), // exponential notation must have normalized mantissa 1076 re(`e[0-9]`), // positive exponent must be signed 1077 //re(`e[+-]0`), // exponent must not have leading zeros 1078 re(`e-[1-6]$`), // not tiny enough for exponential notation 1079 re(`e+(.|1.|20)$`), // not big enough for exponential notation 1080 re(`^-?0\.0000000`), // too tiny, should use exponential notation 1081 re(`^-?[0-9]{22}`), // too big, should use exponential notation 1082 re(`[1-9][0-9]{16}[1-9]`), // too many significant digits in integer 1083 re(`[1-9][0-9.]{17}[1-9]`), // too many significant digits in decimal 1084 // below here for float32 only 1085 re(`[1-9][0-9]{8}[1-9]`), // too many significant digits in integer 1086 re(`[1-9][0-9.]{9}[1-9]`), // too many significant digits in decimal 1087 } 1088 1089 func TestMarshalFloat(t *testing.T) { 1090 //t.Parallel() 1091 nfail := 0 1092 test := func(f float64, bits int) { 1093 vf := interface{}(f) 1094 if bits == 32 { 1095 f = float64(float32(f)) // round 1096 vf = float32(f) 1097 } 1098 bout, err := json.Marshal(vf) 1099 if err != nil { 1100 t.Errorf("Marshal(%T(%g)): %v", vf, vf, err) 1101 nfail++ 1102 return 1103 } 1104 out := string(bout) 1105 1106 // result must convert back to the same float 1107 g, err := strconv.ParseFloat(out, bits) 1108 if err != nil { 1109 t.Errorf("Marshal(%T(%g)) = %q, cannot parse back: %v", vf, vf, out, err) 1110 nfail++ 1111 return 1112 } 1113 if f != g || fmt.Sprint(f) != fmt.Sprint(g) { // fmt.Sprint handles ±0 1114 t.Errorf("Marshal(%T(%g)) = %q (is %g, not %g)", vf, vf, out, float32(g), vf) 1115 nfail++ 1116 return 1117 } 1118 1119 bad := badFloatREs 1120 if bits == 64 { 1121 bad = bad[:len(bad)-2] 1122 } 1123 for _, re := range bad { 1124 if re.MatchString(out) { 1125 t.Errorf("Marshal(%T(%g)) = %q, must not match /%s/", vf, vf, out, re) 1126 nfail++ 1127 return 1128 } 1129 } 1130 } 1131 1132 var ( 1133 bigger = math.Inf(+1) 1134 smaller = math.Inf(-1) 1135 ) 1136 1137 var digits = "1.2345678901234567890123" 1138 for i := len(digits); i >= 2; i-- { 1139 if testing.Short() && i < len(digits)-4 { 1140 break 1141 } 1142 for exp := -30; exp <= 30; exp++ { 1143 for _, sign := range "+-" { 1144 for bits := 32; bits <= 64; bits += 32 { 1145 s := fmt.Sprintf("%c%se%d", sign, digits[:i], exp) 1146 f, err := strconv.ParseFloat(s, bits) 1147 if err != nil { 1148 log.Fatal(err) 1149 } 1150 next := math.Nextafter 1151 if bits == 32 { 1152 next = func(g, h float64) float64 { 1153 return float64(math.Nextafter32(float32(g), float32(h))) 1154 } 1155 } 1156 test(f, bits) 1157 test(next(f, bigger), bits) 1158 test(next(f, smaller), bits) 1159 if nfail > 50 { 1160 t.Fatalf("stopping test early") 1161 } 1162 } 1163 } 1164 } 1165 } 1166 test(0, 64) 1167 test(math.Copysign(0, -1), 64) 1168 test(0, 32) 1169 test(math.Copysign(0, -1), 32) 1170 } 1171 1172 var encodeStringTests = []struct { 1173 in string 1174 out string 1175 }{ 1176 {"\x00", `"\u0000"`}, 1177 {"\x01", `"\u0001"`}, 1178 {"\x02", `"\u0002"`}, 1179 {"\x03", `"\u0003"`}, 1180 {"\x04", `"\u0004"`}, 1181 {"\x05", `"\u0005"`}, 1182 {"\x06", `"\u0006"`}, 1183 {"\x07", `"\u0007"`}, 1184 {"\x08", `"\u0008"`}, 1185 {"\x09", `"\t"`}, 1186 {"\x0a", `"\n"`}, 1187 {"\x0b", `"\u000b"`}, 1188 {"\x0c", `"\u000c"`}, 1189 {"\x0d", `"\r"`}, 1190 {"\x0e", `"\u000e"`}, 1191 {"\x0f", `"\u000f"`}, 1192 {"\x10", `"\u0010"`}, 1193 {"\x11", `"\u0011"`}, 1194 {"\x12", `"\u0012"`}, 1195 {"\x13", `"\u0013"`}, 1196 {"\x14", `"\u0014"`}, 1197 {"\x15", `"\u0015"`}, 1198 {"\x16", `"\u0016"`}, 1199 {"\x17", `"\u0017"`}, 1200 {"\x18", `"\u0018"`}, 1201 {"\x19", `"\u0019"`}, 1202 {"\x1a", `"\u001a"`}, 1203 {"\x1b", `"\u001b"`}, 1204 {"\x1c", `"\u001c"`}, 1205 {"\x1d", `"\u001d"`}, 1206 {"\x1e", `"\u001e"`}, 1207 {"\x1f", `"\u001f"`}, 1208 } 1209 1210 func TestEncodeString(t *testing.T) { 1211 for _, tt := range encodeStringTests { 1212 b, err := json.Marshal(tt.in) 1213 if err != nil { 1214 t.Errorf("Marshal(%q): %v", tt.in, err) 1215 continue 1216 } 1217 out := string(b) 1218 if out != tt.out { 1219 t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out) 1220 } 1221 } 1222 } 1223 1224 type jsonbyte byte 1225 1226 func (b jsonbyte) MarshalJSON() ([]byte, error) { return tenc(`{"JB":%d}`, b) } 1227 1228 type textbyte byte 1229 1230 func (b textbyte) MarshalText() ([]byte, error) { return tenc(`TB:%d`, b) } 1231 1232 type jsonint int 1233 1234 func (i jsonint) MarshalJSON() ([]byte, error) { return tenc(`{"JI":%d}`, i) } 1235 1236 type textint int 1237 1238 func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } 1239 1240 func tenc(format string, a ...interface{}) ([]byte, error) { 1241 var buf bytes.Buffer 1242 fmt.Fprintf(&buf, format, a...) 1243 return buf.Bytes(), nil 1244 } 1245 1246 // Issue 13783 1247 func TestEncodeBytekind(t *testing.T) { 1248 testdata := []struct { 1249 data interface{} 1250 want string 1251 }{ 1252 {byte(7), "7"}, 1253 {jsonbyte(7), `{"JB":7}`}, 1254 {textbyte(4), `"TB:4"`}, 1255 {jsonint(5), `{"JI":5}`}, 1256 {textint(1), `"TI:1"`}, 1257 {[]byte{0, 1}, `"AAE="`}, 1258 1259 {[]jsonbyte{0, 1}, `[{"JB":0},{"JB":1}]`}, 1260 {[][]jsonbyte{{0, 1}, {3}}, `[[{"JB":0},{"JB":1}],[{"JB":3}]]`}, 1261 {[]textbyte{2, 3}, `["TB:2","TB:3"]`}, 1262 1263 {[]jsonint{5, 4}, `[{"JI":5},{"JI":4}]`}, 1264 {[]textint{9, 3}, `["TI:9","TI:3"]`}, 1265 {[]int{9, 3}, `[9,3]`}, 1266 } 1267 for i, d := range testdata { 1268 js, err := json.Marshal(d.data) 1269 if err != nil { 1270 t.Error(err) 1271 continue 1272 } 1273 got, want := string(js), d.want 1274 if got != want { 1275 t.Errorf("%d: got %s, want %s", i, got, want) 1276 } 1277 } 1278 } 1279 1280 // golang.org/issue/8582 1281 func TestEncodePointerString(t *testing.T) { 1282 type stringPointer struct { 1283 N *int64 `json:"n,string"` 1284 } 1285 var n int64 = 42 1286 b, err := json.Marshal(stringPointer{N: &n}) 1287 if err != nil { 1288 t.Fatalf("Marshal: %v", err) 1289 } 1290 if got, want := string(b), `{"n":"42"}`; got != want { 1291 t.Errorf("Marshal = %s, want %s", got, want) 1292 } 1293 var back stringPointer 1294 err = json.Unmarshal(b, &back) 1295 if err != nil { 1296 t.Fatalf("Unmarshal: %v", err) 1297 } 1298 if back.N == nil { 1299 t.Fatalf("Unmarshaled nil N field") 1300 } 1301 if *back.N != 42 { 1302 t.Fatalf("*N = %d; want 42", *back.N) 1303 } 1304 } 1305 1306 type SamePointerNoCycle struct { 1307 Ptr1, Ptr2 *SamePointerNoCycle 1308 } 1309 1310 var samePointerNoCycle = &SamePointerNoCycle{} 1311 1312 type PointerCycle struct { 1313 Ptr *PointerCycle 1314 } 1315 1316 var pointerCycle = &PointerCycle{} 1317 1318 type PointerCycleIndirect struct { 1319 Ptrs []interface{} 1320 } 1321 1322 var pointerCycleIndirect = &PointerCycleIndirect{} 1323 1324 func init() { 1325 ptr := &SamePointerNoCycle{} 1326 samePointerNoCycle.Ptr1 = ptr 1327 samePointerNoCycle.Ptr2 = ptr 1328 1329 pointerCycle.Ptr = pointerCycle 1330 pointerCycleIndirect.Ptrs = []interface{}{pointerCycleIndirect} 1331 } 1332 1333 func TestSamePointerNoCycle(t *testing.T) { 1334 if _, err := json.Marshal(samePointerNoCycle); err != nil { 1335 t.Fatalf("unexpected error: %v", err) 1336 } 1337 } 1338 1339 var unsupportedValues = []interface{}{ 1340 math.NaN(), 1341 math.Inf(-1), 1342 math.Inf(1), 1343 pointerCycle, 1344 pointerCycleIndirect, 1345 } 1346 1347 func TestUnsupportedValues(t *testing.T) { 1348 for _, v := range unsupportedValues { 1349 if _, err := json.Marshal(v); err != nil { 1350 if _, ok := err.(*json.UnsupportedValueError); !ok { 1351 t.Errorf("for %v, got %T want UnsupportedValueError", v, err) 1352 } 1353 } else { 1354 t.Errorf("for %v, expected error", v) 1355 } 1356 } 1357 } 1358 1359 func TestIssue10281(t *testing.T) { 1360 type Foo struct { 1361 N json.Number 1362 } 1363 x := Foo{json.Number(`invalid`)} 1364 1365 b, err := json.Marshal(&x) 1366 if err == nil { 1367 t.Errorf("Marshal(&x) = %#q; want error", b) 1368 } 1369 } 1370 1371 func TestHTMLEscape(t *testing.T) { 1372 var b, want bytes.Buffer 1373 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` 1374 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) 1375 json.HTMLEscape(&b, []byte(m)) 1376 if !bytes.Equal(b.Bytes(), want.Bytes()) { 1377 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) 1378 } 1379 } 1380 1381 type BugA struct { 1382 S string 1383 } 1384 1385 type BugB struct { 1386 BugA 1387 S string 1388 } 1389 1390 type BugC struct { 1391 S string 1392 } 1393 1394 // Legal Go: We never use the repeated embedded field (S). 1395 type BugX struct { 1396 A int 1397 BugA 1398 BugB 1399 } 1400 1401 // golang.org/issue/16042. 1402 // Even if a nil interface value is passed in, as long as 1403 // it implements Marshaler, it should be marshaled. 1404 type nilJSONMarshaler string 1405 1406 func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) { 1407 if nm == nil { 1408 return json.Marshal("0zenil0") 1409 } 1410 return json.Marshal("zenil:" + string(*nm)) 1411 } 1412 1413 // golang.org/issue/34235. 1414 // Even if a nil interface value is passed in, as long as 1415 // it implements encoding.TextMarshaler, it should be marshaled. 1416 type nilTextMarshaler string 1417 1418 func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { 1419 if nm == nil { 1420 return []byte("0zenil0"), nil 1421 } 1422 return []byte("zenil:" + string(*nm)), nil 1423 } 1424 1425 // See golang.org/issue/16042 and golang.org/issue/34235. 1426 func TestNilMarshal(t *testing.T) { 1427 testCases := []struct { 1428 v interface{} 1429 want string 1430 }{ 1431 {v: nil, want: `null`}, 1432 {v: new(float64), want: `0`}, 1433 {v: []interface{}(nil), want: `null`}, 1434 {v: []string(nil), want: `null`}, 1435 {v: map[string]string(nil), want: `null`}, 1436 {v: []byte(nil), want: `null`}, 1437 {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, 1438 {v: struct{ M json.Marshaler }{}, want: `{"M":null}`}, 1439 {v: struct{ M json.Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1440 {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, 1441 {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, 1442 {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1443 {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, 1444 } 1445 1446 for i, tt := range testCases { 1447 out, err := json.Marshal(tt.v) 1448 if err != nil || string(out) != tt.want { 1449 t.Errorf("%d: Marshal(%#v) = %#q, %#v, want %#q, nil", i, tt.v, out, err, tt.want) 1450 continue 1451 } 1452 } 1453 } 1454 1455 // Issue 5245. 1456 func TestEmbeddedBug(t *testing.T) { 1457 v := BugB{ 1458 BugA{"A"}, 1459 "B", 1460 } 1461 b, err := json.Marshal(v) 1462 if err != nil { 1463 t.Fatal("Marshal:", err) 1464 } 1465 want := `{"S":"B"}` 1466 got := string(b) 1467 if got != want { 1468 t.Fatalf("Marshal: got %s want %s", got, want) 1469 } 1470 // Now check that the duplicate field, S, does not appear. 1471 x := BugX{ 1472 A: 23, 1473 } 1474 b, err = json.Marshal(x) 1475 if err != nil { 1476 t.Fatal("Marshal:", err) 1477 } 1478 want = `{"A":23}` 1479 got = string(b) 1480 if got != want { 1481 t.Fatalf("Marshal: got %s want %s", got, want) 1482 } 1483 } 1484 1485 type BugD struct { // Same as BugA after tagging. 1486 XXX string `json:"S"` 1487 } 1488 1489 // BugD's tagged S field should dominate BugA's. 1490 type BugY struct { 1491 BugA 1492 BugD 1493 } 1494 1495 // Test that a field with a tag dominates untagged fields. 1496 func TestTaggedFieldDominates(t *testing.T) { 1497 v := BugY{ 1498 BugA{"BugA"}, 1499 BugD{"BugD"}, 1500 } 1501 b, err := json.Marshal(v) 1502 if err != nil { 1503 t.Fatal("Marshal:", err) 1504 } 1505 want := `{"S":"BugD"}` 1506 got := string(b) 1507 if got != want { 1508 t.Fatalf("Marshal: got %s want %s", got, want) 1509 } 1510 } 1511 1512 // There are no tags here, so S should not appear. 1513 type BugZ struct { 1514 BugA 1515 BugC 1516 BugY // Contains a tagged S field through BugD; should not dominate. 1517 } 1518 1519 func TestDuplicatedFieldDisappears(t *testing.T) { 1520 v := BugZ{ 1521 BugA{"BugA"}, 1522 BugC{"BugC"}, 1523 BugY{ 1524 BugA{"nested BugA"}, 1525 BugD{"nested BugD"}, 1526 }, 1527 } 1528 b, err := json.Marshal(v) 1529 if err != nil { 1530 t.Fatal("Marshal:", err) 1531 } 1532 want := `{}` 1533 got := string(b) 1534 if got != want { 1535 t.Fatalf("Marshal: got %s want %s", got, want) 1536 } 1537 } 1538 1539 func TestAnonymousFields(t *testing.T) { 1540 tests := []struct { 1541 label string // Test name 1542 makeInput func() interface{} // Function to create input value 1543 want string // Expected JSON output 1544 }{{ 1545 // Both S1 and S2 have a field named X. From the perspective of S, 1546 // it is ambiguous which one X refers to. 1547 // This should not serialize either field. 1548 label: "AmbiguousField", 1549 makeInput: func() interface{} { 1550 type ( 1551 S1 struct{ x, X int } 1552 S2 struct{ x, X int } 1553 S struct { 1554 S1 1555 S2 1556 } 1557 ) 1558 return S{S1{1, 2}, S2{3, 4}} 1559 }, 1560 want: `{}`, 1561 }, { 1562 label: "DominantField", 1563 // Both S1 and S2 have a field named X, but since S has an X field as 1564 // well, it takes precedence over S1.X and S2.X. 1565 makeInput: func() interface{} { 1566 type ( 1567 S1 struct{ x, X int } 1568 S2 struct{ x, X int } 1569 S struct { 1570 S1 1571 S2 1572 x, X int 1573 } 1574 ) 1575 return S{S1{1, 2}, S2{3, 4}, 5, 6} 1576 }, 1577 want: `{"X":6}`, 1578 }, { 1579 // Unexported embedded field of non-struct type should not be serialized. 1580 label: "UnexportedEmbeddedInt", 1581 makeInput: func() interface{} { 1582 type ( 1583 myInt int 1584 S struct{ myInt } 1585 ) 1586 return S{5} 1587 }, 1588 want: `{}`, 1589 }, { 1590 // Exported embedded field of non-struct type should be serialized. 1591 label: "ExportedEmbeddedInt", 1592 makeInput: func() interface{} { 1593 type ( 1594 MyInt int 1595 S struct{ MyInt } 1596 ) 1597 return S{5} 1598 }, 1599 want: `{"MyInt":5}`, 1600 }, { 1601 // Unexported embedded field of pointer to non-struct type 1602 // should not be serialized. 1603 label: "UnexportedEmbeddedIntPointer", 1604 makeInput: func() interface{} { 1605 type ( 1606 myInt int 1607 S struct{ *myInt } 1608 ) 1609 s := S{new(myInt)} 1610 *s.myInt = 5 1611 return s 1612 }, 1613 want: `{}`, 1614 }, { 1615 // Exported embedded field of pointer to non-struct type 1616 // should be serialized. 1617 label: "ExportedEmbeddedIntPointer", 1618 makeInput: func() interface{} { 1619 type ( 1620 MyInt int 1621 S struct{ *MyInt } 1622 ) 1623 s := S{new(MyInt)} 1624 *s.MyInt = 5 1625 return s 1626 }, 1627 want: `{"MyInt":5}`, 1628 }, { 1629 // Exported fields of embedded structs should have their 1630 // exported fields be serialized regardless of whether the struct types 1631 // themselves are exported. 1632 label: "EmbeddedStruct", 1633 makeInput: func() interface{} { 1634 type ( 1635 s1 struct{ x, X int } 1636 S2 struct{ y, Y int } 1637 S struct { 1638 s1 1639 S2 1640 } 1641 ) 1642 return S{s1{1, 2}, S2{3, 4}} 1643 }, 1644 want: `{"X":2,"Y":4}`, 1645 }, { 1646 // Exported fields of pointers to embedded structs should have their 1647 // exported fields be serialized regardless of whether the struct types 1648 // themselves are exported. 1649 label: "EmbeddedStructPointer", 1650 makeInput: func() interface{} { 1651 type ( 1652 s1 struct{ x, X int } 1653 S2 struct{ y, Y int } 1654 S struct { 1655 *s1 1656 *S2 1657 } 1658 ) 1659 return S{&s1{1, 2}, &S2{3, 4}} 1660 }, 1661 want: `{"X":2,"Y":4}`, 1662 }, { 1663 // Exported fields on embedded unexported structs at multiple levels 1664 // of nesting should still be serialized. 1665 label: "NestedStructAndInts", 1666 makeInput: func() interface{} { 1667 type ( 1668 MyInt1 int 1669 MyInt2 int 1670 myInt int 1671 s2 struct { 1672 MyInt2 1673 myInt 1674 } 1675 s1 struct { 1676 MyInt1 1677 myInt 1678 s2 1679 } 1680 S struct { 1681 s1 1682 myInt 1683 } 1684 ) 1685 return S{s1{1, 2, s2{3, 4}}, 6} 1686 }, 1687 want: `{"MyInt1":1,"MyInt2":3}`, 1688 }, { 1689 // If an anonymous struct pointer field is nil, we should ignore 1690 // the embedded fields behind it. Not properly doing so may 1691 // result in the wrong output or reflect panics. 1692 label: "EmbeddedFieldBehindNilPointer", 1693 makeInput: func() interface{} { 1694 type ( 1695 S2 struct{ Field string } 1696 S struct{ *S2 } 1697 ) 1698 return S{} 1699 }, 1700 want: `{}`, 1701 }} 1702 1703 for i, tt := range tests { 1704 t.Run(tt.label, func(t *testing.T) { 1705 b, err := json.Marshal(tt.makeInput()) 1706 if err != nil { 1707 t.Fatalf("%d: Marshal() = %v, want nil error", i, err) 1708 } 1709 if string(b) != tt.want { 1710 t.Fatalf("%d: Marshal() = %q, want %q", i, b, tt.want) 1711 } 1712 }) 1713 } 1714 } 1715 1716 type Optionals struct { 1717 Sr string `json:"sr"` 1718 So string `json:"so,omitempty"` 1719 Sw string `json:"-"` 1720 1721 Ir int `json:"omitempty"` // actually named omitempty, not an option 1722 Io int `json:"io,omitempty"` 1723 1724 Slr []string `json:"slr,random"` 1725 Slo []string `json:"slo,omitempty"` 1726 1727 Mr map[string]interface{} `json:"mr"` 1728 Mo map[string]interface{} `json:",omitempty"` 1729 1730 Fr float64 `json:"fr"` 1731 Fo float64 `json:"fo,omitempty"` 1732 1733 Br bool `json:"br"` 1734 Bo bool `json:"bo,omitempty"` 1735 1736 Ur uint `json:"ur"` 1737 Uo uint `json:"uo,omitempty"` 1738 1739 Str struct{} `json:"str"` 1740 Sto struct{} `json:"sto,omitempty"` 1741 } 1742 1743 var optionalsExpected = `{ 1744 "sr": "", 1745 "omitempty": 0, 1746 "slr": null, 1747 "mr": {}, 1748 "fr": 0, 1749 "br": false, 1750 "ur": 0, 1751 "str": {}, 1752 "sto": {} 1753 }` 1754 1755 func TestOmitEmpty(t *testing.T) { 1756 var o Optionals 1757 o.Sw = "something" 1758 o.Mr = map[string]interface{}{} 1759 o.Mo = map[string]interface{}{} 1760 1761 got, err := json.MarshalIndent(&o, "", " ") 1762 if err != nil { 1763 t.Fatal(err) 1764 } 1765 if got := string(got); got != optionalsExpected { 1766 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) 1767 } 1768 } 1769 1770 type testNullStr string 1771 1772 func (v *testNullStr) MarshalJSON() ([]byte, error) { 1773 if *v == "" { 1774 return []byte("null"), nil 1775 } 1776 1777 return []byte(*v), nil 1778 } 1779 1780 func TestIssue147(t *testing.T) { 1781 type T struct { 1782 Field1 string `json:"field1"` 1783 Field2 testNullStr `json:"field2,omitempty"` 1784 } 1785 got, err := json.Marshal(T{ 1786 Field1: "a", 1787 Field2: "b", 1788 }) 1789 if err != nil { 1790 t.Fatal(err) 1791 } 1792 expect, _ := stdjson.Marshal(T{ 1793 Field1: "a", 1794 Field2: "b", 1795 }) 1796 if !bytes.Equal(expect, got) { 1797 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1798 } 1799 } 1800 1801 type testIssue144 struct { 1802 name string 1803 number int64 1804 } 1805 1806 func (v *testIssue144) MarshalJSON() ([]byte, error) { 1807 if v.name != "" { 1808 return json.Marshal(v.name) 1809 } 1810 return json.Marshal(v.number) 1811 } 1812 1813 func TestIssue144(t *testing.T) { 1814 type Embeded struct { 1815 Field *testIssue144 `json:"field,omitempty"` 1816 } 1817 type T struct { 1818 Embeded 1819 } 1820 { 1821 v := T{ 1822 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1823 } 1824 got, err := json.Marshal(v) 1825 if err != nil { 1826 t.Fatal(err) 1827 } 1828 expect, _ := stdjson.Marshal(v) 1829 if !bytes.Equal(expect, got) { 1830 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1831 } 1832 } 1833 { 1834 v := &T{ 1835 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1836 } 1837 got, err := json.Marshal(v) 1838 if err != nil { 1839 t.Fatal(err) 1840 } 1841 expect, _ := stdjson.Marshal(v) 1842 if !bytes.Equal(expect, got) { 1843 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1844 } 1845 } 1846 } 1847 1848 func TestIssue118(t *testing.T) { 1849 type data struct { 1850 Columns []string `json:"columns"` 1851 Rows1 [][]string `json:"rows1"` 1852 Rows2 [][]string `json:"rows2"` 1853 } 1854 v := data{Columns: []string{"1", "2", "3"}} 1855 got, err := json.MarshalIndent(v, "", " ") 1856 if err != nil { 1857 t.Fatal(err) 1858 } 1859 expect, _ := stdjson.MarshalIndent(v, "", " ") 1860 if !bytes.Equal(expect, got) { 1861 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1862 } 1863 } 1864 1865 func TestIssue104(t *testing.T) { 1866 type A struct { 1867 Field1 string 1868 Field2 int 1869 Field3 float64 1870 } 1871 type T struct { 1872 Field A 1873 } 1874 got, err := json.Marshal(T{}) 1875 if err != nil { 1876 t.Fatal(err) 1877 } 1878 expect, _ := stdjson.Marshal(T{}) 1879 if !bytes.Equal(expect, got) { 1880 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1881 } 1882 } 1883 1884 func TestIssue179(t *testing.T) { 1885 data := ` 1886 { 1887 "t": { 1888 "t1": false, 1889 "t2": 0, 1890 "t3": "", 1891 "t4": [], 1892 "t5": null, 1893 "t6": null 1894 } 1895 }` 1896 type T struct { 1897 X struct { 1898 T1 bool `json:"t1,omitempty"` 1899 T2 float64 `json:"t2,omitempty"` 1900 T3 string `json:"t3,omitempty"` 1901 T4 []string `json:"t4,omitempty"` 1902 T5 *struct{} `json:"t5,omitempty"` 1903 T6 interface{} `json:"t6,omitempty"` 1904 } `json:"x"` 1905 } 1906 var v T 1907 if err := stdjson.Unmarshal([]byte(data), &v); err != nil { 1908 t.Fatal(err) 1909 } 1910 var v2 T 1911 if err := json.Unmarshal([]byte(data), &v2); err != nil { 1912 t.Fatal(err) 1913 } 1914 if !reflect.DeepEqual(v, v2) { 1915 t.Fatalf("failed to decode: expected %v got %v", v, v2) 1916 } 1917 b1, err := stdjson.Marshal(v) 1918 if err != nil { 1919 t.Fatal(err) 1920 } 1921 b2, err := json.Marshal(v2) 1922 if err != nil { 1923 t.Fatal(err) 1924 } 1925 if !bytes.Equal(b1, b2) { 1926 t.Fatalf("failed to equal encoded result: expected %q but got %q", b1, b2) 1927 } 1928 } 1929 1930 func TestIssue180(t *testing.T) { 1931 v := struct { 1932 T struct { 1933 T1 bool `json:"t1"` 1934 T2 float64 `json:"t2"` 1935 T3 string `json:"t3"` 1936 T4 []string `json:"t4"` 1937 T5 *struct{} `json:"t5"` 1938 T6 interface{} `json:"t6"` 1939 T7 [][]string `json:"t7"` 1940 } `json:"t"` 1941 }{ 1942 T: struct { 1943 T1 bool `json:"t1"` 1944 T2 float64 `json:"t2"` 1945 T3 string `json:"t3"` 1946 T4 []string `json:"t4"` 1947 T5 *struct{} `json:"t5"` 1948 T6 interface{} `json:"t6"` 1949 T7 [][]string `json:"t7"` 1950 }{ 1951 T4: []string{}, 1952 T7: [][]string{ 1953 []string{""}, 1954 []string{"hello", "world"}, 1955 []string{}, 1956 }, 1957 }, 1958 } 1959 b1, err := stdjson.MarshalIndent(v, "", "\t") 1960 if err != nil { 1961 t.Fatal(err) 1962 } 1963 b2, err := json.MarshalIndent(v, "", "\t") 1964 if err != nil { 1965 t.Fatal(err) 1966 } 1967 if !bytes.Equal(b1, b2) { 1968 t.Fatalf("failed to equal encoded result: expected %s but got %s", string(b1), string(b2)) 1969 } 1970 } 1971 1972 func TestIssue235(t *testing.T) { 1973 type TaskMessage struct { 1974 Type string 1975 Payload map[string]interface{} 1976 UniqueKey string 1977 } 1978 msg := TaskMessage{ 1979 Payload: map[string]interface{}{ 1980 "sent_at": map[string]interface{}{ 1981 "Time": "0001-01-01T00:00:00Z", 1982 "Valid": false, 1983 }, 1984 }, 1985 } 1986 if _, err := json.Marshal(msg); err != nil { 1987 t.Fatal(err) 1988 } 1989 } 1990 1991 func TestEncodeMapKeyTypeInterface(t *testing.T) { 1992 if _, err := json.Marshal(map[interface{}]interface{}{"a": 1}); err == nil { 1993 t.Fatal("expected error") 1994 } 1995 } 1996 1997 type marshalContextKey struct{} 1998 1999 type marshalContextStructType struct{} 2000 2001 func (t *marshalContextStructType) MarshalJSON(ctx context.Context) ([]byte, error) { 2002 v := ctx.Value(marshalContextKey{}) 2003 s, ok := v.(string) 2004 if !ok { 2005 return nil, fmt.Errorf("failed to propagate parent context.Context") 2006 } 2007 if s != "hello" { 2008 return nil, fmt.Errorf("failed to propagate parent context.Context") 2009 } 2010 return []byte(`"success"`), nil 2011 } 2012 2013 func TestEncodeContextOption(t *testing.T) { 2014 t.Run("MarshalContext", func(t *testing.T) { 2015 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2016 b, err := json.MarshalContext(ctx, &marshalContextStructType{}) 2017 if err != nil { 2018 t.Fatal(err) 2019 } 2020 if string(b) != `"success"` { 2021 t.Fatal("failed to encode with MarshalerContext") 2022 } 2023 }) 2024 t.Run("EncodeContext", func(t *testing.T) { 2025 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2026 buf := bytes.NewBuffer([]byte{}) 2027 if err := json.NewEncoder(buf).EncodeContext(ctx, &marshalContextStructType{}); err != nil { 2028 t.Fatal(err) 2029 } 2030 if buf.String() != "\"success\"\n" { 2031 t.Fatal("failed to encode with EncodeContext") 2032 } 2033 }) 2034 } 2035 2036 func TestInterfaceWithPointer(t *testing.T) { 2037 var ( 2038 ivalue int = 10 2039 uvalue uint = 20 2040 svalue string = "value" 2041 bvalue bool = true 2042 fvalue float32 = 3.14 2043 nvalue json.Number = "1.23" 2044 structv = struct{ A int }{A: 10} 2045 slice = []int{1, 2, 3, 4} 2046 array = [4]int{1, 2, 3, 4} 2047 mapvalue = map[string]int{"a": 1} 2048 ) 2049 data := map[string]interface{}{ 2050 "ivalue": ivalue, 2051 "uvalue": uvalue, 2052 "svalue": svalue, 2053 "bvalue": bvalue, 2054 "fvalue": fvalue, 2055 "nvalue": nvalue, 2056 "struct": structv, 2057 "slice": slice, 2058 "array": array, 2059 "map": mapvalue, 2060 "pivalue": &ivalue, 2061 "puvalue": &uvalue, 2062 "psvalue": &svalue, 2063 "pbvalue": &bvalue, 2064 "pfvalue": &fvalue, 2065 "pnvalue": &nvalue, 2066 "pstruct": &structv, 2067 "pslice": &slice, 2068 "parray": &array, 2069 "pmap": &mapvalue, 2070 } 2071 expected, err := stdjson.Marshal(data) 2072 if err != nil { 2073 t.Fatal(err) 2074 } 2075 actual, err := json.Marshal(data) 2076 if err != nil { 2077 t.Fatal(err) 2078 } 2079 assertEq(t, "interface{}", string(expected), string(actual)) 2080 } 2081 2082 func TestIssue263(t *testing.T) { 2083 type Foo struct { 2084 A []string `json:"a"` 2085 B int `json:"b"` 2086 } 2087 2088 type MyStruct struct { 2089 Foo *Foo `json:"foo,omitempty"` 2090 } 2091 2092 s := MyStruct{ 2093 Foo: &Foo{ 2094 A: []string{"ls -lah"}, 2095 B: 0, 2096 }, 2097 } 2098 expected, err := stdjson.Marshal(s) 2099 if err != nil { 2100 t.Fatal(err) 2101 } 2102 actual, err := json.Marshal(s) 2103 if err != nil { 2104 t.Fatal(err) 2105 } 2106 if !bytes.Equal(expected, actual) { 2107 t.Fatalf("expected:[%s] but got:[%s]", string(expected), string(actual)) 2108 } 2109 } 2110 2111 func TestEmbeddedNotFirstField(t *testing.T) { 2112 type Embedded struct { 2113 Has bool `json:"has"` 2114 } 2115 type T struct { 2116 X int `json:"is"` 2117 Embedded `json:"child"` 2118 } 2119 p := T{X: 10, Embedded: Embedded{Has: true}} 2120 expected, err := stdjson.Marshal(&p) 2121 if err != nil { 2122 t.Fatal(err) 2123 } 2124 got, err := json.Marshal(&p) 2125 if err != nil { 2126 t.Fatal(err) 2127 } 2128 if !bytes.Equal(expected, got) { 2129 t.Fatalf("failed to encode embedded structure. expected = %q but got %q", expected, got) 2130 } 2131 } 2132 2133 type implementedMethodIface interface { 2134 M() 2135 } 2136 2137 type implementedIfaceType struct { 2138 A int 2139 B string 2140 } 2141 2142 func (implementedIfaceType) M() {} 2143 2144 func TestImplementedMethodInterfaceType(t *testing.T) { 2145 data := []implementedIfaceType{implementedIfaceType{}} 2146 expected, err := stdjson.Marshal(data) 2147 if err != nil { 2148 t.Fatal(err) 2149 } 2150 got, err := json.Marshal(data) 2151 if err != nil { 2152 t.Fatal(err) 2153 } 2154 if !bytes.Equal(expected, got) { 2155 t.Fatalf("failed to encode implemented method interface type. expected:[%q] but got:[%q]", expected, got) 2156 } 2157 } 2158 2159 func TestEmptyStructInterface(t *testing.T) { 2160 expected, err := stdjson.Marshal([]interface{}{struct{}{}}) 2161 if err != nil { 2162 t.Fatal(err) 2163 } 2164 got, err := json.Marshal([]interface{}{struct{}{}}) 2165 if err != nil { 2166 t.Fatal(err) 2167 } 2168 if !bytes.Equal(expected, got) { 2169 t.Fatalf("failed to encode empty struct interface. expected:[%q] but got:[%q]", expected, got) 2170 } 2171 } 2172 2173 func TestIssue290(t *testing.T) { 2174 type Issue290 interface { 2175 A() 2176 } 2177 var a struct { 2178 A Issue290 2179 } 2180 expected, err := stdjson.Marshal(a) 2181 if err != nil { 2182 t.Fatal(err) 2183 } 2184 got, err := json.Marshal(a) 2185 if err != nil { 2186 t.Fatal(err) 2187 } 2188 if !bytes.Equal(expected, got) { 2189 t.Fatalf("failed to encode non empty interface. expected = %q but got %q", expected, got) 2190 } 2191 } 2192 2193 func TestIssue299(t *testing.T) { 2194 t.Run("conflict second field", func(t *testing.T) { 2195 type Embedded struct { 2196 ID string `json:"id"` 2197 Name map[string]string `json:"name"` 2198 } 2199 type Container struct { 2200 Embedded 2201 Name string `json:"name"` 2202 } 2203 c := &Container{ 2204 Embedded: Embedded{ 2205 ID: "1", 2206 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2207 }, 2208 Name: "Hi", 2209 } 2210 expected, _ := stdjson.Marshal(c) 2211 got, err := json.Marshal(c) 2212 if err != nil { 2213 t.Fatal(err) 2214 } 2215 if !bytes.Equal(expected, got) { 2216 t.Fatalf("expected %q but got %q", expected, got) 2217 } 2218 }) 2219 t.Run("conflict map field", func(t *testing.T) { 2220 type Embedded struct { 2221 Name map[string]string `json:"name"` 2222 } 2223 type Container struct { 2224 Embedded 2225 Name string `json:"name"` 2226 } 2227 c := &Container{ 2228 Embedded: Embedded{ 2229 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2230 }, 2231 Name: "Hi", 2232 } 2233 expected, _ := stdjson.Marshal(c) 2234 got, err := json.Marshal(c) 2235 if err != nil { 2236 t.Fatal(err) 2237 } 2238 if !bytes.Equal(expected, got) { 2239 t.Fatalf("expected %q but got %q", expected, got) 2240 } 2241 }) 2242 t.Run("conflict slice field", func(t *testing.T) { 2243 type Embedded struct { 2244 Name []string `json:"name"` 2245 } 2246 type Container struct { 2247 Embedded 2248 Name string `json:"name"` 2249 } 2250 c := &Container{ 2251 Embedded: Embedded{ 2252 Name: []string{"Hello"}, 2253 }, 2254 Name: "Hi", 2255 } 2256 expected, _ := stdjson.Marshal(c) 2257 got, err := json.Marshal(c) 2258 if err != nil { 2259 t.Fatal(err) 2260 } 2261 if !bytes.Equal(expected, got) { 2262 t.Fatalf("expected %q but got %q", expected, got) 2263 } 2264 }) 2265 } 2266 2267 func TestRecursivePtrHead(t *testing.T) { 2268 type User struct { 2269 Account *string `json:"account"` 2270 Password *string `json:"password"` 2271 Nickname *string `json:"nickname"` 2272 Address *string `json:"address,omitempty"` 2273 Friends []*User `json:"friends,omitempty"` 2274 } 2275 user1Account, user1Password, user1Nickname := "abcdef", "123456", "user1" 2276 user1 := &User{ 2277 Account: &user1Account, 2278 Password: &user1Password, 2279 Nickname: &user1Nickname, 2280 Address: nil, 2281 } 2282 user2Account, user2Password, user2Nickname := "ghijkl", "123456", "user2" 2283 user2 := &User{ 2284 Account: &user2Account, 2285 Password: &user2Password, 2286 Nickname: &user2Nickname, 2287 Address: nil, 2288 } 2289 user1.Friends = []*User{user2} 2290 expected, err := stdjson.Marshal(user1) 2291 if err != nil { 2292 t.Fatal(err) 2293 } 2294 got, err := json.Marshal(user1) 2295 if err != nil { 2296 t.Fatal(err) 2297 } 2298 if !bytes.Equal(expected, got) { 2299 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2300 } 2301 } 2302 2303 func TestMarshalIndent(t *testing.T) { 2304 v := map[string]map[string]interface{}{ 2305 "a": { 2306 "b": "1", 2307 "c": map[string]interface{}{ 2308 "d": "1", 2309 }, 2310 }, 2311 } 2312 expected, err := stdjson.MarshalIndent(v, "", " ") 2313 if err != nil { 2314 t.Fatal(err) 2315 } 2316 got, err := json.MarshalIndent(v, "", " ") 2317 if err != nil { 2318 t.Fatal(err) 2319 } 2320 if !bytes.Equal(expected, got) { 2321 t.Fatalf("expected: %q but got %q", expected, got) 2322 } 2323 } 2324 2325 type issue318Embedded struct { 2326 _ [64]byte 2327 } 2328 2329 type issue318 struct { 2330 issue318Embedded `json:"-"` 2331 ID issue318MarshalText `json:"id,omitempty"` 2332 } 2333 2334 type issue318MarshalText struct { 2335 ID string 2336 } 2337 2338 func (i issue318MarshalText) MarshalText() ([]byte, error) { 2339 return []byte(i.ID), nil 2340 } 2341 2342 func TestIssue318(t *testing.T) { 2343 v := issue318{ 2344 ID: issue318MarshalText{ID: "1"}, 2345 } 2346 b, err := json.Marshal(v) 2347 if err != nil { 2348 t.Fatal(err) 2349 } 2350 expected := `{"id":"1"}` 2351 if string(b) != expected { 2352 t.Fatalf("failed to encode. expected %s but got %s", expected, string(b)) 2353 } 2354 } 2355 2356 type emptyStringMarshaler struct { 2357 Value stringMarshaler `json:"value,omitempty"` 2358 } 2359 2360 type stringMarshaler string 2361 2362 func (s stringMarshaler) MarshalJSON() ([]byte, error) { 2363 return []byte(`"` + s + `"`), nil 2364 } 2365 2366 func TestEmptyStringMarshaler(t *testing.T) { 2367 value := emptyStringMarshaler{} 2368 expected, err := stdjson.Marshal(value) 2369 assertErr(t, err) 2370 got, err := json.Marshal(value) 2371 assertErr(t, err) 2372 assertEq(t, "struct", string(expected), string(got)) 2373 } 2374 2375 func TestIssue324(t *testing.T) { 2376 type T struct { 2377 FieldA *string `json:"fieldA,omitempty"` 2378 FieldB *string `json:"fieldB,omitempty"` 2379 FieldC *bool `json:"fieldC"` 2380 FieldD []string `json:"fieldD,omitempty"` 2381 } 2382 v := &struct { 2383 Code string `json:"code"` 2384 *T 2385 }{ 2386 T: &T{}, 2387 } 2388 var sv = "Test Field" 2389 v.Code = "Test" 2390 v.T.FieldB = &sv 2391 expected, err := stdjson.Marshal(v) 2392 if err != nil { 2393 t.Fatal(err) 2394 } 2395 got, err := json.Marshal(v) 2396 if err != nil { 2397 t.Fatal(err) 2398 } 2399 if !bytes.Equal(expected, got) { 2400 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2401 } 2402 } 2403 2404 func TestIssue339(t *testing.T) { 2405 type T1 struct { 2406 *big.Int 2407 } 2408 type T2 struct { 2409 T1 T1 `json:"T1"` 2410 } 2411 v := T2{T1{Int: big.NewInt(10000)}} 2412 b, err := json.Marshal(&v) 2413 assertErr(t, err) 2414 got := string(b) 2415 expected := `{"T1":10000}` 2416 if got != expected { 2417 t.Errorf("unexpected result: %v != %v", got, expected) 2418 } 2419 } 2420 2421 func TestIssue376(t *testing.T) { 2422 type Container struct { 2423 V interface{} `json:"value"` 2424 } 2425 type MapOnly struct { 2426 Map map[string]int64 `json:"map"` 2427 } 2428 b, err := json.Marshal(Container{MapOnly{}}) 2429 if err != nil { 2430 t.Fatal(err) 2431 } 2432 got := string(b) 2433 expected := `{"value":{"map":null}}` 2434 if got != expected { 2435 t.Errorf("unexpected result: %v != %v", got, expected) 2436 } 2437 } 2438 2439 type Issue370 struct { 2440 String string 2441 Valid bool 2442 } 2443 2444 func (i *Issue370) MarshalJSON() ([]byte, error) { 2445 if !i.Valid { 2446 return json.Marshal(nil) 2447 } 2448 return json.Marshal(i.String) 2449 } 2450 2451 func TestIssue370(t *testing.T) { 2452 v := []struct { 2453 V Issue370 2454 }{ 2455 {V: Issue370{String: "test", Valid: true}}, 2456 } 2457 b, err := json.Marshal(v) 2458 if err != nil { 2459 t.Fatal(err) 2460 } 2461 got := string(b) 2462 expected := `[{"V":"test"}]` 2463 if got != expected { 2464 t.Errorf("unexpected result: %v != %v", got, expected) 2465 } 2466 } 2467 2468 func TestIssue374(t *testing.T) { 2469 r := io.MultiReader(strings.NewReader(strings.Repeat(" ", 505)+`"\u`), strings.NewReader(`0000"`)) 2470 var v interface{} 2471 if err := json.NewDecoder(r).Decode(&v); err != nil { 2472 t.Fatal(err) 2473 } 2474 got := v.(string) 2475 expected := "\u0000" 2476 if got != expected { 2477 t.Errorf("unexpected result: %q != %q", got, expected) 2478 } 2479 } 2480 2481 func TestIssue381(t *testing.T) { 2482 var v struct { 2483 Field0 bool 2484 Field1 bool 2485 Field2 bool 2486 Field3 bool 2487 Field4 bool 2488 Field5 bool 2489 Field6 bool 2490 Field7 bool 2491 Field8 bool 2492 Field9 bool 2493 Field10 bool 2494 Field11 bool 2495 Field12 bool 2496 Field13 bool 2497 Field14 bool 2498 Field15 bool 2499 Field16 bool 2500 Field17 bool 2501 Field18 bool 2502 Field19 bool 2503 Field20 bool 2504 Field21 bool 2505 Field22 bool 2506 Field23 bool 2507 Field24 bool 2508 Field25 bool 2509 Field26 bool 2510 Field27 bool 2511 Field28 bool 2512 Field29 bool 2513 Field30 bool 2514 Field31 bool 2515 Field32 bool 2516 Field33 bool 2517 Field34 bool 2518 Field35 bool 2519 Field36 bool 2520 Field37 bool 2521 Field38 bool 2522 Field39 bool 2523 Field40 bool 2524 Field41 bool 2525 Field42 bool 2526 Field43 bool 2527 Field44 bool 2528 Field45 bool 2529 Field46 bool 2530 Field47 bool 2531 Field48 bool 2532 Field49 bool 2533 Field50 bool 2534 Field51 bool 2535 Field52 bool 2536 Field53 bool 2537 Field54 bool 2538 Field55 bool 2539 Field56 bool 2540 Field57 bool 2541 Field58 bool 2542 Field59 bool 2543 Field60 bool 2544 Field61 bool 2545 Field62 bool 2546 Field63 bool 2547 Field64 bool 2548 Field65 bool 2549 Field66 bool 2550 Field67 bool 2551 Field68 bool 2552 Field69 bool 2553 Field70 bool 2554 Field71 bool 2555 Field72 bool 2556 Field73 bool 2557 Field74 bool 2558 Field75 bool 2559 Field76 bool 2560 Field77 bool 2561 Field78 bool 2562 Field79 bool 2563 Field80 bool 2564 Field81 bool 2565 Field82 bool 2566 Field83 bool 2567 Field84 bool 2568 Field85 bool 2569 Field86 bool 2570 Field87 bool 2571 Field88 bool 2572 Field89 bool 2573 Field90 bool 2574 Field91 bool 2575 Field92 bool 2576 Field93 bool 2577 Field94 bool 2578 Field95 bool 2579 Field96 bool 2580 Field97 bool 2581 Field98 bool 2582 Field99 bool 2583 } 2584 2585 // test encoder cache issue, not related to encoder 2586 b, err := json.Marshal(v) 2587 if err != nil { 2588 t.Errorf("failed to marshal %s", err.Error()) 2589 t.FailNow() 2590 } 2591 2592 std, err := stdjson.Marshal(v) 2593 if err != nil { 2594 t.Errorf("failed to marshal with encoding/json %s", err.Error()) 2595 t.FailNow() 2596 } 2597 2598 if !bytes.Equal(std, b) { 2599 t.Errorf("encoding result not equal to encoding/json") 2600 t.FailNow() 2601 } 2602 } 2603 2604 func TestIssue386(t *testing.T) { 2605 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)"}` 2606 var a struct { 2607 Date *string `json:"date"` 2608 Platform *string `json:"platform"` 2609 Summary string `json:"summary"` 2610 Name string `json:"name"` 2611 } 2612 err := json.NewDecoder(strings.NewReader(raw)).Decode(&a) 2613 if err != nil { 2614 t.Error(err) 2615 } 2616 } 2617 2618 type customMapKey string 2619 2620 func (b customMapKey) MarshalJSON() ([]byte, error) { 2621 return []byte("[]"), nil 2622 } 2623 2624 func TestCustomMarshalForMapKey(t *testing.T) { 2625 m := map[customMapKey]string{customMapKey("skipcustom"): "test"} 2626 expected, err := stdjson.Marshal(m) 2627 assertErr(t, err) 2628 got, err := json.Marshal(m) 2629 assertErr(t, err) 2630 assertEq(t, "custom map key", string(expected), string(got)) 2631 } 2632 2633 func TestIssue391(t *testing.T) { 2634 type A struct { 2635 X string `json:"x,omitempty"` 2636 } 2637 type B struct { 2638 A 2639 } 2640 type C struct { 2641 X []int `json:"x,omitempty"` 2642 } 2643 for _, tc := range []struct { 2644 name string 2645 in interface{} 2646 out string 2647 }{ 2648 {in: struct{ B }{}, out: "{}"}, 2649 {in: struct { 2650 B 2651 Y string `json:"y"` 2652 }{}, out: `{"y":""}`}, 2653 {in: struct { 2654 Y string `json:"y"` 2655 B 2656 }{}, out: `{"y":""}`}, 2657 {in: struct{ C }{}, out: "{}"}, 2658 } { 2659 t.Run(tc.name, func(t *testing.T) { 2660 b, err := json.Marshal(tc.in) 2661 assertErr(t, err) 2662 assertEq(t, "unexpected result", tc.out, string(b)) 2663 }) 2664 } 2665 } 2666 2667 func TestIssue417(t *testing.T) { 2668 x := map[string]string{ 2669 "b": "b", 2670 "a": "a", 2671 } 2672 b, err := json.MarshalIndentWithOption(x, "", " ", json.UnorderedMap()) 2673 assertErr(t, err) 2674 2675 var y map[string]string 2676 err = json.Unmarshal(b, &y) 2677 assertErr(t, err) 2678 2679 assertEq(t, "key b", "b", y["b"]) 2680 assertEq(t, "key a", "a", y["a"]) 2681 } 2682 2683 func TestIssue426(t *testing.T) { 2684 type I interface { 2685 Foo() 2686 } 2687 type A struct { 2688 I 2689 Val string 2690 } 2691 var s A 2692 s.Val = "456" 2693 2694 b, _ := json.Marshal(s) 2695 assertEq(t, "unexpected result", `{"I":null,"Val":"456"}`, string(b)) 2696 } 2697 2698 func TestIssue441(t *testing.T) { 2699 type A struct { 2700 Y string `json:"y,omitempty"` 2701 } 2702 2703 type B struct { 2704 X *int `json:"x,omitempty"` 2705 A 2706 Z int `json:"z,omitempty"` 2707 } 2708 2709 b, err := json.Marshal(B{}) 2710 assertErr(t, err) 2711 assertEq(t, "unexpected result", "{}", string(b)) 2712 }