github.com/grbit/go-json@v0.11.0/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/grbit/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 // due to using stdlib encoding/json as a fallback 1352 if err == nil { 1353 t.Errorf("for %v, got %T want UnsupportedValueError", v, err) 1354 } 1355 } else { 1356 t.Errorf("for %v, expected error", v) 1357 } 1358 } 1359 } 1360 1361 func TestIssue10281(t *testing.T) { 1362 type Foo struct { 1363 N json.Number 1364 } 1365 x := Foo{json.Number(`invalid`)} 1366 1367 b, err := json.Marshal(&x) 1368 if err == nil { 1369 t.Errorf("Marshal(&x) = %#q; want error", b) 1370 } 1371 } 1372 1373 func TestHTMLEscape(t *testing.T) { 1374 var b, want bytes.Buffer 1375 m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` 1376 want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) 1377 json.HTMLEscape(&b, []byte(m)) 1378 if !bytes.Equal(b.Bytes(), want.Bytes()) { 1379 t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) 1380 } 1381 } 1382 1383 type BugA struct { 1384 S string 1385 } 1386 1387 type BugB struct { 1388 BugA 1389 S string 1390 } 1391 1392 type BugC struct { 1393 S string 1394 } 1395 1396 // Legal Go: We never use the repeated embedded field (S). 1397 type BugX struct { 1398 A int 1399 BugA 1400 BugB 1401 } 1402 1403 // golang.org/issue/16042. 1404 // Even if a nil interface value is passed in, as long as 1405 // it implements Marshaler, it should be marshaled. 1406 type nilJSONMarshaler string 1407 1408 func (nm *nilJSONMarshaler) MarshalJSON() ([]byte, error) { 1409 if nm == nil { 1410 return json.Marshal("0zenil0") 1411 } 1412 return json.Marshal("zenil:" + string(*nm)) 1413 } 1414 1415 // golang.org/issue/34235. 1416 // Even if a nil interface value is passed in, as long as 1417 // it implements encoding.TextMarshaler, it should be marshaled. 1418 type nilTextMarshaler string 1419 1420 func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { 1421 if nm == nil { 1422 return []byte("0zenil0"), nil 1423 } 1424 return []byte("zenil:" + string(*nm)), nil 1425 } 1426 1427 // See golang.org/issue/16042 and golang.org/issue/34235. 1428 func TestNilMarshal(t *testing.T) { 1429 testCases := []struct { 1430 v interface{} 1431 want string 1432 }{ 1433 {v: nil, want: `null`}, 1434 {v: new(float64), want: `0`}, 1435 {v: []interface{}(nil), want: `null`}, 1436 {v: []string(nil), want: `null`}, 1437 {v: map[string]string(nil), want: `null`}, 1438 {v: []byte(nil), want: `null`}, 1439 {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, 1440 {v: struct{ M json.Marshaler }{}, want: `{"M":null}`}, 1441 {v: struct{ M json.Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1442 {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, 1443 {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, 1444 {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, 1445 {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, 1446 } 1447 1448 for i, tt := range testCases { 1449 out, err := json.Marshal(tt.v) 1450 if err != nil || string(out) != tt.want { 1451 t.Errorf("%d: Marshal(%#v) = %#q, %#v, want %#q, nil", i, tt.v, out, err, tt.want) 1452 continue 1453 } 1454 } 1455 } 1456 1457 // Issue 5245. 1458 func TestEmbeddedBug(t *testing.T) { 1459 v := BugB{ 1460 BugA{"A"}, 1461 "B", 1462 } 1463 b, err := json.Marshal(v) 1464 if err != nil { 1465 t.Fatal("Marshal:", err) 1466 } 1467 want := `{"S":"B"}` 1468 got := string(b) 1469 if got != want { 1470 t.Fatalf("Marshal: got %s want %s", got, want) 1471 } 1472 // Now check that the duplicate field, S, does not appear. 1473 x := BugX{ 1474 A: 23, 1475 } 1476 b, err = json.Marshal(x) 1477 if err != nil { 1478 t.Fatal("Marshal:", err) 1479 } 1480 want = `{"A":23}` 1481 got = string(b) 1482 if got != want { 1483 t.Fatalf("Marshal: got %s want %s", got, want) 1484 } 1485 } 1486 1487 type BugD struct { // Same as BugA after tagging. 1488 XXX string `json:"S"` 1489 } 1490 1491 // BugD's tagged S field should dominate BugA's. 1492 type BugY struct { 1493 BugA 1494 BugD 1495 } 1496 1497 // Test that a field with a tag dominates untagged fields. 1498 func TestTaggedFieldDominates(t *testing.T) { 1499 v := BugY{ 1500 BugA{"BugA"}, 1501 BugD{"BugD"}, 1502 } 1503 b, err := json.Marshal(v) 1504 if err != nil { 1505 t.Fatal("Marshal:", err) 1506 } 1507 want := `{"S":"BugD"}` 1508 got := string(b) 1509 if got != want { 1510 t.Fatalf("Marshal: got %s want %s", got, want) 1511 } 1512 } 1513 1514 // There are no tags here, so S should not appear. 1515 type BugZ struct { 1516 BugA 1517 BugC 1518 BugY // Contains a tagged S field through BugD; should not dominate. 1519 } 1520 1521 func TestDuplicatedFieldDisappears(t *testing.T) { 1522 v := BugZ{ 1523 BugA{"BugA"}, 1524 BugC{"BugC"}, 1525 BugY{ 1526 BugA{"nested BugA"}, 1527 BugD{"nested BugD"}, 1528 }, 1529 } 1530 b, err := json.Marshal(v) 1531 if err != nil { 1532 t.Fatal("Marshal:", err) 1533 } 1534 want := `{}` 1535 got := string(b) 1536 if got != want { 1537 t.Fatalf("Marshal: got %s want %s", got, want) 1538 } 1539 } 1540 1541 func TestAnonymousFields(t *testing.T) { 1542 tests := []struct { 1543 label string // Test name 1544 makeInput func() interface{} // Function to create input value 1545 want string // Expected JSON output 1546 }{{ 1547 // Both S1 and S2 have a field named X. From the perspective of S, 1548 // it is ambiguous which one X refers to. 1549 // This should not serialize either field. 1550 label: "AmbiguousField", 1551 makeInput: func() interface{} { 1552 type ( 1553 S1 struct{ x, X int } 1554 S2 struct{ x, X int } 1555 S struct { 1556 S1 1557 S2 1558 } 1559 ) 1560 return S{S1{1, 2}, S2{3, 4}} 1561 }, 1562 want: `{}`, 1563 }, { 1564 label: "DominantField", 1565 // Both S1 and S2 have a field named X, but since S has an X field as 1566 // well, it takes precedence over S1.X and S2.X. 1567 makeInput: func() interface{} { 1568 type ( 1569 S1 struct{ x, X int } 1570 S2 struct{ x, X int } 1571 S struct { 1572 S1 1573 S2 1574 x, X int 1575 } 1576 ) 1577 return S{S1{1, 2}, S2{3, 4}, 5, 6} 1578 }, 1579 want: `{"X":6}`, 1580 }, { 1581 // Unexported embedded field of non-struct type should not be serialized. 1582 label: "UnexportedEmbeddedInt", 1583 makeInput: func() interface{} { 1584 type ( 1585 myInt int 1586 S struct{ myInt } 1587 ) 1588 return S{5} 1589 }, 1590 want: `{}`, 1591 }, { 1592 // Exported embedded field of non-struct type should be serialized. 1593 label: "ExportedEmbeddedInt", 1594 makeInput: func() interface{} { 1595 type ( 1596 MyInt int 1597 S struct{ MyInt } 1598 ) 1599 return S{5} 1600 }, 1601 want: `{"MyInt":5}`, 1602 }, { 1603 // Unexported embedded field of pointer to non-struct type 1604 // should not be serialized. 1605 label: "UnexportedEmbeddedIntPointer", 1606 makeInput: func() interface{} { 1607 type ( 1608 myInt int 1609 S struct{ *myInt } 1610 ) 1611 s := S{new(myInt)} 1612 *s.myInt = 5 1613 return s 1614 }, 1615 want: `{}`, 1616 }, { 1617 // Exported embedded field of pointer to non-struct type 1618 // should be serialized. 1619 label: "ExportedEmbeddedIntPointer", 1620 makeInput: func() interface{} { 1621 type ( 1622 MyInt int 1623 S struct{ *MyInt } 1624 ) 1625 s := S{new(MyInt)} 1626 *s.MyInt = 5 1627 return s 1628 }, 1629 want: `{"MyInt":5}`, 1630 }, { 1631 // Exported fields of embedded structs should have their 1632 // exported fields be serialized regardless of whether the struct types 1633 // themselves are exported. 1634 label: "EmbeddedStruct", 1635 makeInput: func() interface{} { 1636 type ( 1637 s1 struct{ x, X int } 1638 S2 struct{ y, Y int } 1639 S struct { 1640 s1 1641 S2 1642 } 1643 ) 1644 return S{s1{1, 2}, S2{3, 4}} 1645 }, 1646 want: `{"X":2,"Y":4}`, 1647 }, { 1648 // Exported fields of pointers to embedded structs should have their 1649 // exported fields be serialized regardless of whether the struct types 1650 // themselves are exported. 1651 label: "EmbeddedStructPointer", 1652 makeInput: func() interface{} { 1653 type ( 1654 s1 struct{ x, X int } 1655 S2 struct{ y, Y int } 1656 S struct { 1657 *s1 1658 *S2 1659 } 1660 ) 1661 return S{&s1{1, 2}, &S2{3, 4}} 1662 }, 1663 want: `{"X":2,"Y":4}`, 1664 }, { 1665 // Exported fields on embedded unexported structs at multiple levels 1666 // of nesting should still be serialized. 1667 label: "NestedStructAndInts", 1668 makeInput: func() interface{} { 1669 type ( 1670 MyInt1 int 1671 MyInt2 int 1672 myInt int 1673 s2 struct { 1674 MyInt2 1675 myInt 1676 } 1677 s1 struct { 1678 MyInt1 1679 myInt 1680 s2 1681 } 1682 S struct { 1683 s1 1684 myInt 1685 } 1686 ) 1687 return S{s1{1, 2, s2{3, 4}}, 6} 1688 }, 1689 want: `{"MyInt1":1,"MyInt2":3}`, 1690 }, { 1691 // If an anonymous struct pointer field is nil, we should ignore 1692 // the embedded fields behind it. Not properly doing so may 1693 // result in the wrong output or reflect panics. 1694 label: "EmbeddedFieldBehindNilPointer", 1695 makeInput: func() interface{} { 1696 type ( 1697 S2 struct{ Field string } 1698 S struct{ *S2 } 1699 ) 1700 return S{} 1701 }, 1702 want: `{}`, 1703 }} 1704 1705 for i, tt := range tests { 1706 t.Run(tt.label, func(t *testing.T) { 1707 b, err := json.Marshal(tt.makeInput()) 1708 if err != nil { 1709 t.Fatalf("%d: Marshal() = %v, want nil error", i, err) 1710 } 1711 if string(b) != tt.want { 1712 t.Fatalf("%d: Marshal() = %q, want %q", i, b, tt.want) 1713 } 1714 }) 1715 } 1716 } 1717 1718 type Optionals struct { 1719 Sr string `json:"sr"` 1720 So string `json:"so,omitempty"` 1721 Sw string `json:"-"` 1722 1723 Ir int `json:"omitempty"` // actually named omitempty, not an option 1724 Io int `json:"io,omitempty"` 1725 1726 Slr []string `json:"slr,random"` 1727 Slo []string `json:"slo,omitempty"` 1728 1729 Mr map[string]interface{} `json:"mr"` 1730 Mo map[string]interface{} `json:",omitempty"` 1731 1732 Fr float64 `json:"fr"` 1733 Fo float64 `json:"fo,omitempty"` 1734 1735 Br bool `json:"br"` 1736 Bo bool `json:"bo,omitempty"` 1737 1738 Ur uint `json:"ur"` 1739 Uo uint `json:"uo,omitempty"` 1740 1741 Str struct{} `json:"str"` 1742 Sto struct{} `json:"sto,omitempty"` 1743 } 1744 1745 var optionalsExpected = `{ 1746 "sr": "", 1747 "omitempty": 0, 1748 "slr": null, 1749 "mr": {}, 1750 "fr": 0, 1751 "br": false, 1752 "ur": 0, 1753 "str": {}, 1754 "sto": {} 1755 }` 1756 1757 func TestOmitEmpty(t *testing.T) { 1758 var o Optionals 1759 o.Sw = "something" 1760 o.Mr = map[string]interface{}{} 1761 o.Mo = map[string]interface{}{} 1762 1763 got, err := json.MarshalIndent(&o, "", " ") 1764 if err != nil { 1765 t.Fatal(err) 1766 } 1767 if got := string(got); got != optionalsExpected { 1768 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) 1769 } 1770 } 1771 1772 type testNullStr string 1773 1774 func (v *testNullStr) MarshalJSON() ([]byte, error) { 1775 if *v == "" { 1776 return []byte("null"), nil 1777 } 1778 1779 return []byte(*v), nil 1780 } 1781 1782 func TestIssue147(t *testing.T) { 1783 type T struct { 1784 Field1 string `json:"field1"` 1785 Field2 testNullStr `json:"field2,omitempty"` 1786 } 1787 got, err := json.Marshal(T{ 1788 Field1: "a", 1789 Field2: "b", 1790 }) 1791 if err != nil { 1792 t.Fatal(err) 1793 } 1794 expect, _ := stdjson.Marshal(T{ 1795 Field1: "a", 1796 Field2: "b", 1797 }) 1798 if !bytes.Equal(expect, got) { 1799 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1800 } 1801 } 1802 1803 type testIssue144 struct { 1804 name string 1805 number int64 1806 } 1807 1808 func (v *testIssue144) MarshalJSON() ([]byte, error) { 1809 if v.name != "" { 1810 return json.Marshal(v.name) 1811 } 1812 return json.Marshal(v.number) 1813 } 1814 1815 func TestIssue144(t *testing.T) { 1816 type Embeded struct { 1817 Field *testIssue144 `json:"field,omitempty"` 1818 } 1819 type T struct { 1820 Embeded 1821 } 1822 { 1823 v := T{ 1824 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1825 } 1826 got, err := json.Marshal(v) 1827 if err != nil { 1828 t.Fatal(err) 1829 } 1830 expect, _ := stdjson.Marshal(v) 1831 if !bytes.Equal(expect, got) { 1832 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1833 } 1834 } 1835 { 1836 v := &T{ 1837 Embeded: Embeded{Field: &testIssue144{name: "hoge"}}, 1838 } 1839 got, err := json.Marshal(v) 1840 if err != nil { 1841 t.Fatal(err) 1842 } 1843 expect, _ := stdjson.Marshal(v) 1844 if !bytes.Equal(expect, got) { 1845 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1846 } 1847 } 1848 } 1849 1850 func TestIssue118(t *testing.T) { 1851 type data struct { 1852 Columns []string `json:"columns"` 1853 Rows1 [][]string `json:"rows1"` 1854 Rows2 [][]string `json:"rows2"` 1855 } 1856 v := data{Columns: []string{"1", "2", "3"}} 1857 got, err := json.MarshalIndent(v, "", " ") 1858 if err != nil { 1859 t.Fatal(err) 1860 } 1861 expect, _ := stdjson.MarshalIndent(v, "", " ") 1862 if !bytes.Equal(expect, got) { 1863 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1864 } 1865 } 1866 1867 func TestIssue104(t *testing.T) { 1868 type A struct { 1869 Field1 string 1870 Field2 int 1871 Field3 float64 1872 } 1873 type T struct { 1874 Field A 1875 } 1876 got, err := json.Marshal(T{}) 1877 if err != nil { 1878 t.Fatal(err) 1879 } 1880 expect, _ := stdjson.Marshal(T{}) 1881 if !bytes.Equal(expect, got) { 1882 t.Fatalf("expect %q but got %q", string(expect), string(got)) 1883 } 1884 } 1885 1886 func TestIssue179(t *testing.T) { 1887 data := ` 1888 { 1889 "t": { 1890 "t1": false, 1891 "t2": 0, 1892 "t3": "", 1893 "t4": [], 1894 "t5": null, 1895 "t6": null 1896 } 1897 }` 1898 type T struct { 1899 X struct { 1900 T1 bool `json:"t1,omitempty"` 1901 T2 float64 `json:"t2,omitempty"` 1902 T3 string `json:"t3,omitempty"` 1903 T4 []string `json:"t4,omitempty"` 1904 T5 *struct{} `json:"t5,omitempty"` 1905 T6 interface{} `json:"t6,omitempty"` 1906 } `json:"x"` 1907 } 1908 var v T 1909 if err := stdjson.Unmarshal([]byte(data), &v); err != nil { 1910 t.Fatal(err) 1911 } 1912 var v2 T 1913 if err := json.Unmarshal([]byte(data), &v2); err != nil { 1914 t.Fatal(err) 1915 } 1916 if !reflect.DeepEqual(v, v2) { 1917 t.Fatalf("failed to decode: expected %v got %v", v, v2) 1918 } 1919 b1, err := stdjson.Marshal(v) 1920 if err != nil { 1921 t.Fatal(err) 1922 } 1923 b2, err := json.Marshal(v2) 1924 if err != nil { 1925 t.Fatal(err) 1926 } 1927 if !bytes.Equal(b1, b2) { 1928 t.Fatalf("failed to equal encoded result: expected %q but got %q", b1, b2) 1929 } 1930 } 1931 1932 func TestIssue180(t *testing.T) { 1933 v := struct { 1934 T struct { 1935 T1 bool `json:"t1"` 1936 T2 float64 `json:"t2"` 1937 T3 string `json:"t3"` 1938 T4 []string `json:"t4"` 1939 T5 *struct{} `json:"t5"` 1940 T6 interface{} `json:"t6"` 1941 T7 [][]string `json:"t7"` 1942 } `json:"t"` 1943 }{ 1944 T: struct { 1945 T1 bool `json:"t1"` 1946 T2 float64 `json:"t2"` 1947 T3 string `json:"t3"` 1948 T4 []string `json:"t4"` 1949 T5 *struct{} `json:"t5"` 1950 T6 interface{} `json:"t6"` 1951 T7 [][]string `json:"t7"` 1952 }{ 1953 T4: []string{}, 1954 T7: [][]string{ 1955 []string{""}, 1956 []string{"hello", "world"}, 1957 []string{}, 1958 }, 1959 }, 1960 } 1961 b1, err := stdjson.MarshalIndent(v, "", "\t") 1962 if err != nil { 1963 t.Fatal(err) 1964 } 1965 b2, err := json.MarshalIndent(v, "", "\t") 1966 if err != nil { 1967 t.Fatal(err) 1968 } 1969 if !bytes.Equal(b1, b2) { 1970 t.Fatalf("failed to equal encoded result: expected %s but got %s", string(b1), string(b2)) 1971 } 1972 } 1973 1974 func TestIssue235(t *testing.T) { 1975 type TaskMessage struct { 1976 Type string 1977 Payload map[string]interface{} 1978 UniqueKey string 1979 } 1980 msg := TaskMessage{ 1981 Payload: map[string]interface{}{ 1982 "sent_at": map[string]interface{}{ 1983 "Time": "0001-01-01T00:00:00Z", 1984 "Valid": false, 1985 }, 1986 }, 1987 } 1988 if _, err := json.Marshal(msg); err != nil { 1989 t.Fatal(err) 1990 } 1991 } 1992 1993 func TestEncodeMapKeyTypeInterface(t *testing.T) { 1994 if _, err := json.Marshal(map[interface{}]interface{}{"a": 1}); err == nil { 1995 t.Fatal("expected error") 1996 } 1997 } 1998 1999 type marshalContextKey struct{} 2000 2001 type marshalContextStructType struct{} 2002 2003 func (t *marshalContextStructType) MarshalJSON(ctx context.Context) ([]byte, error) { 2004 v := ctx.Value(marshalContextKey{}) 2005 s, ok := v.(string) 2006 if !ok { 2007 return nil, fmt.Errorf("failed to propagate parent context.Context") 2008 } 2009 if s != "hello" { 2010 return nil, fmt.Errorf("failed to propagate parent context.Context") 2011 } 2012 return []byte(`"success"`), nil 2013 } 2014 2015 func TestEncodeContextOption(t *testing.T) { 2016 t.Run("MarshalContext", func(t *testing.T) { 2017 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2018 b, err := json.MarshalContext(ctx, &marshalContextStructType{}) 2019 if err != nil { 2020 t.Fatal(err) 2021 } 2022 if string(b) != `"success"` { 2023 t.Fatal("failed to encode with MarshalerContext") 2024 } 2025 }) 2026 t.Run("EncodeContext", func(t *testing.T) { 2027 ctx := context.WithValue(context.Background(), marshalContextKey{}, "hello") 2028 buf := bytes.NewBuffer([]byte{}) 2029 if err := json.NewEncoder(buf).EncodeContext(ctx, &marshalContextStructType{}); err != nil { 2030 t.Fatal(err) 2031 } 2032 if buf.String() != "\"success\"\n" { 2033 t.Fatal("failed to encode with EncodeContext") 2034 } 2035 }) 2036 } 2037 2038 func TestInterfaceWithPointer(t *testing.T) { 2039 var ( 2040 ivalue int = 10 2041 uvalue uint = 20 2042 svalue string = "value" 2043 bvalue bool = true 2044 fvalue float32 = 3.14 2045 nvalue json.Number = "1.23" 2046 structv = struct{ A int }{A: 10} 2047 slice = []int{1, 2, 3, 4} 2048 array = [4]int{1, 2, 3, 4} 2049 mapvalue = map[string]int{"a": 1} 2050 ) 2051 data := map[string]interface{}{ 2052 "ivalue": ivalue, 2053 "uvalue": uvalue, 2054 "svalue": svalue, 2055 "bvalue": bvalue, 2056 "fvalue": fvalue, 2057 "nvalue": nvalue, 2058 "struct": structv, 2059 "slice": slice, 2060 "array": array, 2061 "map": mapvalue, 2062 "pivalue": &ivalue, 2063 "puvalue": &uvalue, 2064 "psvalue": &svalue, 2065 "pbvalue": &bvalue, 2066 "pfvalue": &fvalue, 2067 "pnvalue": &nvalue, 2068 "pstruct": &structv, 2069 "pslice": &slice, 2070 "parray": &array, 2071 "pmap": &mapvalue, 2072 } 2073 expected, err := stdjson.Marshal(data) 2074 if err != nil { 2075 t.Fatal(err) 2076 } 2077 actual, err := json.Marshal(data) 2078 if err != nil { 2079 t.Fatal(err) 2080 } 2081 assertEq(t, "interface{}", string(expected), string(actual)) 2082 } 2083 2084 func TestIssue263(t *testing.T) { 2085 type Foo struct { 2086 A []string `json:"a"` 2087 B int `json:"b"` 2088 } 2089 2090 type MyStruct struct { 2091 Foo *Foo `json:"foo,omitempty"` 2092 } 2093 2094 s := MyStruct{ 2095 Foo: &Foo{ 2096 A: []string{"ls -lah"}, 2097 B: 0, 2098 }, 2099 } 2100 expected, err := stdjson.Marshal(s) 2101 if err != nil { 2102 t.Fatal(err) 2103 } 2104 actual, err := json.Marshal(s) 2105 if err != nil { 2106 t.Fatal(err) 2107 } 2108 if !bytes.Equal(expected, actual) { 2109 t.Fatalf("expected:[%s] but got:[%s]", string(expected), string(actual)) 2110 } 2111 } 2112 2113 func TestEmbeddedNotFirstField(t *testing.T) { 2114 type Embedded struct { 2115 Has bool `json:"has"` 2116 } 2117 type T struct { 2118 X int `json:"is"` 2119 Embedded `json:"child"` 2120 } 2121 p := T{X: 10, Embedded: Embedded{Has: true}} 2122 expected, err := stdjson.Marshal(&p) 2123 if err != nil { 2124 t.Fatal(err) 2125 } 2126 got, err := json.Marshal(&p) 2127 if err != nil { 2128 t.Fatal(err) 2129 } 2130 if !bytes.Equal(expected, got) { 2131 t.Fatalf("failed to encode embedded structure. expected = %q but got %q", expected, got) 2132 } 2133 } 2134 2135 type implementedMethodIface interface { 2136 M() 2137 } 2138 2139 type implementedIfaceType struct { 2140 A int 2141 B string 2142 } 2143 2144 func (implementedIfaceType) M() {} 2145 2146 func TestImplementedMethodInterfaceType(t *testing.T) { 2147 data := []implementedIfaceType{implementedIfaceType{}} 2148 expected, err := stdjson.Marshal(data) 2149 if err != nil { 2150 t.Fatal(err) 2151 } 2152 got, err := json.Marshal(data) 2153 if err != nil { 2154 t.Fatal(err) 2155 } 2156 if !bytes.Equal(expected, got) { 2157 t.Fatalf("failed to encode implemented method interface type. expected:[%q] but got:[%q]", expected, got) 2158 } 2159 } 2160 2161 func TestEmptyStructInterface(t *testing.T) { 2162 expected, err := stdjson.Marshal([]interface{}{struct{}{}}) 2163 if err != nil { 2164 t.Fatal(err) 2165 } 2166 got, err := json.Marshal([]interface{}{struct{}{}}) 2167 if err != nil { 2168 t.Fatal(err) 2169 } 2170 if !bytes.Equal(expected, got) { 2171 t.Fatalf("failed to encode empty struct interface. expected:[%q] but got:[%q]", expected, got) 2172 } 2173 } 2174 2175 func TestIssue290(t *testing.T) { 2176 type Issue290 interface { 2177 A() 2178 } 2179 var a struct { 2180 A Issue290 2181 } 2182 expected, err := stdjson.Marshal(a) 2183 if err != nil { 2184 t.Fatal(err) 2185 } 2186 got, err := json.Marshal(a) 2187 if err != nil { 2188 t.Fatal(err) 2189 } 2190 if !bytes.Equal(expected, got) { 2191 t.Fatalf("failed to encode non empty interface. expected = %q but got %q", expected, got) 2192 } 2193 } 2194 2195 func TestIssue299(t *testing.T) { 2196 t.Run("conflict second field", func(t *testing.T) { 2197 type Embedded struct { 2198 ID string `json:"id"` 2199 Name map[string]string `json:"name"` 2200 } 2201 type Container struct { 2202 Embedded 2203 Name string `json:"name"` 2204 } 2205 c := &Container{ 2206 Embedded: Embedded{ 2207 ID: "1", 2208 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2209 }, 2210 Name: "Hi", 2211 } 2212 expected, _ := stdjson.Marshal(c) 2213 got, err := json.Marshal(c) 2214 if err != nil { 2215 t.Fatal(err) 2216 } 2217 if !bytes.Equal(expected, got) { 2218 t.Fatalf("expected %q but got %q", expected, got) 2219 } 2220 }) 2221 t.Run("conflict map field", func(t *testing.T) { 2222 type Embedded struct { 2223 Name map[string]string `json:"name"` 2224 } 2225 type Container struct { 2226 Embedded 2227 Name string `json:"name"` 2228 } 2229 c := &Container{ 2230 Embedded: Embedded{ 2231 Name: map[string]string{"en": "Hello", "es": "Hola"}, 2232 }, 2233 Name: "Hi", 2234 } 2235 expected, _ := stdjson.Marshal(c) 2236 got, err := json.Marshal(c) 2237 if err != nil { 2238 t.Fatal(err) 2239 } 2240 if !bytes.Equal(expected, got) { 2241 t.Fatalf("expected %q but got %q", expected, got) 2242 } 2243 }) 2244 t.Run("conflict slice field", func(t *testing.T) { 2245 type Embedded struct { 2246 Name []string `json:"name"` 2247 } 2248 type Container struct { 2249 Embedded 2250 Name string `json:"name"` 2251 } 2252 c := &Container{ 2253 Embedded: Embedded{ 2254 Name: []string{"Hello"}, 2255 }, 2256 Name: "Hi", 2257 } 2258 expected, _ := stdjson.Marshal(c) 2259 got, err := json.Marshal(c) 2260 if err != nil { 2261 t.Fatal(err) 2262 } 2263 if !bytes.Equal(expected, got) { 2264 t.Fatalf("expected %q but got %q", expected, got) 2265 } 2266 }) 2267 } 2268 2269 func TestRecursivePtrHead(t *testing.T) { 2270 type User struct { 2271 Account *string `json:"account"` 2272 Password *string `json:"password"` 2273 Nickname *string `json:"nickname"` 2274 Address *string `json:"address,omitempty"` 2275 Friends []*User `json:"friends,omitempty"` 2276 } 2277 user1Account, user1Password, user1Nickname := "abcdef", "123456", "user1" 2278 user1 := &User{ 2279 Account: &user1Account, 2280 Password: &user1Password, 2281 Nickname: &user1Nickname, 2282 Address: nil, 2283 } 2284 user2Account, user2Password, user2Nickname := "ghijkl", "123456", "user2" 2285 user2 := &User{ 2286 Account: &user2Account, 2287 Password: &user2Password, 2288 Nickname: &user2Nickname, 2289 Address: nil, 2290 } 2291 user1.Friends = []*User{user2} 2292 expected, err := stdjson.Marshal(user1) 2293 if err != nil { 2294 t.Fatal(err) 2295 } 2296 got, err := json.Marshal(user1) 2297 if err != nil { 2298 t.Fatal(err) 2299 } 2300 if !bytes.Equal(expected, got) { 2301 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2302 } 2303 } 2304 2305 func TestMarshalIndent(t *testing.T) { 2306 v := map[string]map[string]interface{}{ 2307 "a": { 2308 "b": "1", 2309 "c": map[string]interface{}{ 2310 "d": "1", 2311 }, 2312 }, 2313 } 2314 expected, err := stdjson.MarshalIndent(v, "", " ") 2315 if err != nil { 2316 t.Fatal(err) 2317 } 2318 got, err := json.MarshalIndent(v, "", " ") 2319 if err != nil { 2320 t.Fatal(err) 2321 } 2322 if !bytes.Equal(expected, got) { 2323 t.Fatalf("expected: %q but got %q", expected, got) 2324 } 2325 } 2326 2327 type issue318Embedded struct { 2328 _ [64]byte 2329 } 2330 2331 type issue318 struct { 2332 issue318Embedded `json:"-"` 2333 ID issue318MarshalText `json:"id,omitempty"` 2334 } 2335 2336 type issue318MarshalText struct { 2337 ID string 2338 } 2339 2340 func (i issue318MarshalText) MarshalText() ([]byte, error) { 2341 return []byte(i.ID), nil 2342 } 2343 2344 func TestIssue318(t *testing.T) { 2345 v := issue318{ 2346 ID: issue318MarshalText{ID: "1"}, 2347 } 2348 b, err := json.Marshal(v) 2349 if err != nil { 2350 t.Fatal(err) 2351 } 2352 expected := `{"id":"1"}` 2353 if string(b) != expected { 2354 t.Fatalf("failed to encode. expected %s but got %s", expected, string(b)) 2355 } 2356 } 2357 2358 type emptyStringMarshaler struct { 2359 Value stringMarshaler `json:"value,omitempty"` 2360 } 2361 2362 type stringMarshaler string 2363 2364 func (s stringMarshaler) MarshalJSON() ([]byte, error) { 2365 return []byte(`"` + s + `"`), nil 2366 } 2367 2368 func TestEmptyStringMarshaler(t *testing.T) { 2369 value := emptyStringMarshaler{} 2370 expected, err := stdjson.Marshal(value) 2371 assertErr(t, err) 2372 got, err := json.Marshal(value) 2373 assertErr(t, err) 2374 assertEq(t, "struct", string(expected), string(got)) 2375 } 2376 2377 func TestIssue324(t *testing.T) { 2378 type T struct { 2379 FieldA *string `json:"fieldA,omitempty"` 2380 FieldB *string `json:"fieldB,omitempty"` 2381 FieldC *bool `json:"fieldC"` 2382 FieldD []string `json:"fieldD,omitempty"` 2383 } 2384 v := &struct { 2385 Code string `json:"code"` 2386 *T 2387 }{ 2388 T: &T{}, 2389 } 2390 var sv = "Test Field" 2391 v.Code = "Test" 2392 v.T.FieldB = &sv 2393 expected, err := stdjson.Marshal(v) 2394 if err != nil { 2395 t.Fatal(err) 2396 } 2397 got, err := json.Marshal(v) 2398 if err != nil { 2399 t.Fatal(err) 2400 } 2401 if !bytes.Equal(expected, got) { 2402 t.Fatalf("failed to encode. expected %q but got %q", expected, got) 2403 } 2404 } 2405 2406 func TestIssue339(t *testing.T) { 2407 type T1 struct { 2408 *big.Int 2409 } 2410 type T2 struct { 2411 T1 T1 `json:"T1"` 2412 } 2413 v := T2{T1{Int: big.NewInt(10000)}} 2414 b, err := json.Marshal(&v) 2415 assertErr(t, err) 2416 got := string(b) 2417 expected := `{"T1":10000}` 2418 if got != expected { 2419 t.Errorf("unexpected result: %v != %v", got, expected) 2420 } 2421 } 2422 2423 func TestIssue376(t *testing.T) { 2424 type Container struct { 2425 V interface{} `json:"value"` 2426 } 2427 type MapOnly struct { 2428 Map map[string]int64 `json:"map"` 2429 } 2430 b, err := json.Marshal(Container{MapOnly{}}) 2431 if err != nil { 2432 t.Fatal(err) 2433 } 2434 got := string(b) 2435 expected := `{"value":{"map":null}}` 2436 if got != expected { 2437 t.Errorf("unexpected result: %v != %v", got, expected) 2438 } 2439 } 2440 2441 type Issue370 struct { 2442 String string 2443 Valid bool 2444 } 2445 2446 func (i *Issue370) MarshalJSON() ([]byte, error) { 2447 if !i.Valid { 2448 return json.Marshal(nil) 2449 } 2450 return json.Marshal(i.String) 2451 } 2452 2453 func TestIssue370(t *testing.T) { 2454 v := []struct { 2455 V Issue370 2456 }{ 2457 {V: Issue370{String: "test", Valid: true}}, 2458 } 2459 b, err := json.Marshal(v) 2460 if err != nil { 2461 t.Fatal(err) 2462 } 2463 got := string(b) 2464 expected := `[{"V":"test"}]` 2465 if got != expected { 2466 t.Errorf("unexpected result: %v != %v", got, expected) 2467 } 2468 } 2469 2470 func TestIssue374(t *testing.T) { 2471 r := io.MultiReader(strings.NewReader(strings.Repeat(" ", 505)+`"\u`), strings.NewReader(`0000"`)) 2472 var v interface{} 2473 if err := json.NewDecoder(r).Decode(&v); err != nil { 2474 t.Fatal(err) 2475 } 2476 got := v.(string) 2477 expected := "\u0000" 2478 if got != expected { 2479 t.Errorf("unexpected result: %q != %q", got, expected) 2480 } 2481 } 2482 2483 func TestIssue381(t *testing.T) { 2484 var v struct { 2485 Field0 bool 2486 Field1 bool 2487 Field2 bool 2488 Field3 bool 2489 Field4 bool 2490 Field5 bool 2491 Field6 bool 2492 Field7 bool 2493 Field8 bool 2494 Field9 bool 2495 Field10 bool 2496 Field11 bool 2497 Field12 bool 2498 Field13 bool 2499 Field14 bool 2500 Field15 bool 2501 Field16 bool 2502 Field17 bool 2503 Field18 bool 2504 Field19 bool 2505 Field20 bool 2506 Field21 bool 2507 Field22 bool 2508 Field23 bool 2509 Field24 bool 2510 Field25 bool 2511 Field26 bool 2512 Field27 bool 2513 Field28 bool 2514 Field29 bool 2515 Field30 bool 2516 Field31 bool 2517 Field32 bool 2518 Field33 bool 2519 Field34 bool 2520 Field35 bool 2521 Field36 bool 2522 Field37 bool 2523 Field38 bool 2524 Field39 bool 2525 Field40 bool 2526 Field41 bool 2527 Field42 bool 2528 Field43 bool 2529 Field44 bool 2530 Field45 bool 2531 Field46 bool 2532 Field47 bool 2533 Field48 bool 2534 Field49 bool 2535 Field50 bool 2536 Field51 bool 2537 Field52 bool 2538 Field53 bool 2539 Field54 bool 2540 Field55 bool 2541 Field56 bool 2542 Field57 bool 2543 Field58 bool 2544 Field59 bool 2545 Field60 bool 2546 Field61 bool 2547 Field62 bool 2548 Field63 bool 2549 Field64 bool 2550 Field65 bool 2551 Field66 bool 2552 Field67 bool 2553 Field68 bool 2554 Field69 bool 2555 Field70 bool 2556 Field71 bool 2557 Field72 bool 2558 Field73 bool 2559 Field74 bool 2560 Field75 bool 2561 Field76 bool 2562 Field77 bool 2563 Field78 bool 2564 Field79 bool 2565 Field80 bool 2566 Field81 bool 2567 Field82 bool 2568 Field83 bool 2569 Field84 bool 2570 Field85 bool 2571 Field86 bool 2572 Field87 bool 2573 Field88 bool 2574 Field89 bool 2575 Field90 bool 2576 Field91 bool 2577 Field92 bool 2578 Field93 bool 2579 Field94 bool 2580 Field95 bool 2581 Field96 bool 2582 Field97 bool 2583 Field98 bool 2584 Field99 bool 2585 } 2586 2587 // test encoder cache issue, not related to encoder 2588 b, err := json.Marshal(v) 2589 if err != nil { 2590 t.Errorf("failed to marshal %s", err.Error()) 2591 t.FailNow() 2592 } 2593 2594 std, err := stdjson.Marshal(v) 2595 if err != nil { 2596 t.Errorf("failed to marshal with encoding/json %s", err.Error()) 2597 t.FailNow() 2598 } 2599 2600 if !bytes.Equal(std, b) { 2601 t.Errorf("encoding result not equal to encoding/json") 2602 t.FailNow() 2603 } 2604 } 2605 2606 func TestIssue386(t *testing.T) { 2607 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)"}` 2608 var a struct { 2609 Date *string `json:"date"` 2610 Platform *string `json:"platform"` 2611 Summary string `json:"summary"` 2612 Name string `json:"name"` 2613 } 2614 err := json.NewDecoder(strings.NewReader(raw)).Decode(&a) 2615 if err != nil { 2616 t.Error(err) 2617 } 2618 } 2619 2620 type customMapKey string 2621 2622 func (b customMapKey) MarshalJSON() ([]byte, error) { 2623 return []byte("[]"), nil 2624 } 2625 2626 func TestCustomMarshalForMapKey(t *testing.T) { 2627 m := map[customMapKey]string{customMapKey("skipcustom"): "test"} 2628 expected, err := stdjson.Marshal(m) 2629 assertErr(t, err) 2630 got, err := json.Marshal(m) 2631 assertErr(t, err) 2632 assertEq(t, "custom map key", string(expected), string(got)) 2633 } 2634 2635 func TestIssue391(t *testing.T) { 2636 type A struct { 2637 X string `json:"x,omitempty"` 2638 } 2639 type B struct { 2640 A 2641 } 2642 type C struct { 2643 X []int `json:"x,omitempty"` 2644 } 2645 for _, tc := range []struct { 2646 name string 2647 in interface{} 2648 out string 2649 }{ 2650 {in: struct{ B }{}, out: "{}"}, 2651 {in: struct { 2652 B 2653 Y string `json:"y"` 2654 }{}, out: `{"y":""}`}, 2655 {in: struct { 2656 Y string `json:"y"` 2657 B 2658 }{}, out: `{"y":""}`}, 2659 {in: struct{ C }{}, out: "{}"}, 2660 } { 2661 t.Run(tc.name, func(t *testing.T) { 2662 b, err := json.Marshal(tc.in) 2663 assertErr(t, err) 2664 assertEq(t, "unexpected result", tc.out, string(b)) 2665 }) 2666 } 2667 } 2668 2669 func TestIssue417(t *testing.T) { 2670 x := map[string]string{ 2671 "b": "b", 2672 "a": "a", 2673 } 2674 b, err := json.MarshalIndentWithOption(x, "", " ", json.UnorderedMap()) 2675 assertErr(t, err) 2676 2677 var y map[string]string 2678 err = json.Unmarshal(b, &y) 2679 assertErr(t, err) 2680 2681 assertEq(t, "key b", "b", y["b"]) 2682 assertEq(t, "key a", "a", y["a"]) 2683 } 2684 2685 func TestIssue426(t *testing.T) { 2686 type I interface { 2687 Foo() 2688 } 2689 type A struct { 2690 I 2691 Val string 2692 } 2693 var s A 2694 s.Val = "456" 2695 2696 b, _ := json.Marshal(s) 2697 assertEq(t, "unexpected result", `{"I":null,"Val":"456"}`, string(b)) 2698 } 2699 2700 func TestIssue441(t *testing.T) { 2701 type A struct { 2702 Y string `json:"y,omitempty"` 2703 } 2704 2705 type B struct { 2706 X *int `json:"x,omitempty"` 2707 A 2708 Z int `json:"z,omitempty"` 2709 } 2710 2711 b, err := json.Marshal(B{}) 2712 assertErr(t, err) 2713 assertEq(t, "unexpected result", "{}", string(b)) 2714 }