| 149 | | ############################################################################## |
| | 304 | |
| | 305 | |
| | 306 | # |
| | 307 | # JSON Boolean |
| | 308 | # |
| | 309 | |
| | 310 | package JSON::Boolean; |
| | 311 | |
| | 312 | my %Installed; |
| | 313 | |
| | 314 | sub _overrride_overload { |
| | 315 | return if ($Installed{ $_[0] }++); |
| | 316 | |
| | 317 | my $boolean = $_[0] . '::Boolean'; |
| | 318 | |
| | 319 | eval sprintf(q| |
| | 320 | package %s; |
| | 321 | use overload ( |
| | 322 | '""' => sub { ${$_[0]} == 1 ? 'true' : 'false' }, |
| | 323 | 'eq' => sub { |
| | 324 | my ($obj, $op) = ref ($_[0]) ? ($_[0], $_[1]) : ($_[1], $_[0]); |
| | 325 | if ($op eq 'true' or $op eq 'false') { |
| | 326 | return "$obj" eq 'true' ? 'true' eq $op : 'false' eq $op; |
| | 327 | } |
| | 328 | else { |
| | 329 | return $obj ? 1 == $op : 0 == $op; |
| | 330 | } |
| | 331 | }, |
| | 332 | ); |
| | 333 | |, $boolean); |
| | 334 | |
| | 335 | if ($@) { Carp::croak $@; } |
| | 336 | |
| | 337 | return 1; |
| | 338 | } |
| | 339 | |
| | 340 | |
| | 341 | # |
| | 342 | # Helper classes for Backend Module (PP) |
| | 343 | # |
| | 344 | |
| | 345 | package JSON::Backend::PP; |
| | 346 | |
| | 347 | sub init { |
| | 348 | local $^W; |
| | 349 | no strict qw(refs); |
| | 350 | *{"JSON::decode_json"} = \&{"JSON::PP::decode_json"}; |
| | 351 | *{"JSON::encode_json"} = \&{"JSON::PP::encode_json"}; |
| | 352 | *{"JSON::PP::is_xs"} = sub { 0 }; |
| | 353 | *{"JSON::PP::is_pp"} = sub { 1 }; |
| | 354 | return 1; |
| | 355 | } |
| | 356 | |
| | 357 | # |
| | 358 | # To save memory, the below lines are read only when XS backend is used. |
| | 359 | # |
| | 360 | |
| | 361 | package JSON; |
| | 362 | |
| | 363 | 1; |
| | 364 | __DATA__ |
| | 365 | |
| | 366 | |
| | 367 | # |
| | 368 | # Helper classes for Backend Module (XS) |
| | 369 | # |
| | 370 | |
| | 371 | package JSON::Backend::XS; |
| | 372 | |
| | 373 | use constant INDENT_LENGTH_FLAG => 15 << 12; |
| | 374 | |
| | 375 | use constant UNSUPPORTED_ENCODE_FLAG => { |
| | 376 | ESCAPE_SLASH => 0x00000010, |
| | 377 | ALLOW_BIGNUM => 0x00000020, |
| | 378 | AS_NONBLESSED => 0x00000040, |
| | 379 | EXPANDED => 0x10000000, # for developer's |
| | 380 | }; |
| | 381 | |
| | 382 | use constant UNSUPPORTED_DECODE_FLAG => { |
| | 383 | LOOSE => 0x00000001, |
| | 384 | ALLOW_BIGNUM => 0x00000002, |
| | 385 | ALLOW_BAREKEY => 0x00000004, |
| | 386 | ALLOW_SINGLEQUOTE => 0x00000008, |
| | 387 | EXPANDED => 0x20000000, # for developer's |
| | 388 | }; |
| | 389 | |
| | 390 | |
| | 391 | sub init { |
| | 392 | local $^W; |
| | 393 | no strict qw(refs); |
| | 394 | *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"}; |
| | 395 | *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"}; |
| | 396 | *{"JSON::XS::is_xs"} = sub { 1 }; |
| | 397 | *{"JSON::XS::is_pp"} = sub { 0 }; |
| | 398 | return 1; |
| | 399 | } |
| | 400 | |
| | 401 | |
| | 402 | sub support_by_pp { |
| | 403 | my ($class, @methods) = @_; |
| | 404 | |
| | 405 | local $^W; |
| | 406 | no strict qw(refs); |
| | 407 | |
| | 408 | push @JSON::Backend::XS::Supportable::ISA, 'JSON'; |
| | 409 | |
| | 410 | my $pkg = 'JSON::Backend::XS::Supportable'; |
| | 411 | |
| | 412 | *{JSON::new} = sub { |
| | 413 | my $proto = new JSON::XS; $$proto = 0; |
| | 414 | bless $proto, $pkg; |
| | 415 | }; |
| | 416 | |
| | 417 | for my $method (@methods) { |
| | 418 | my $flag = uc($method); |
| | 419 | my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0); |
| | 420 | $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0); |
| | 421 | |
| | 422 | next unless($type); |
| | 423 | |
| | 424 | $pkg->_make_unsupported_method($method => $type); |
| | 425 | } |
| | 426 | |
| | 427 | push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean); |
| | 428 | push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean); |
| | 429 | |
| | 430 | $JSON::DEBUG and Carp::carp("set -support_by_pp mode."); |
| | 431 | |
| | 432 | return 1; |
| | 433 | } |
| | 434 | |
| | 435 | |
| | 436 | |
| | 437 | |
| | 438 | # |
| | 439 | # Helper classes for XS |
| | 440 | # |
| | 441 | |
| | 442 | package JSON::Backend::XS::Supportable; |
| | 443 | |
| | 444 | |
| | 445 | my $JSON_XS_encode_orignal = \&JSON::XS::encode; |
| | 446 | my $JSON_XS_decode_orignal = \&JSON::XS::decode; |
| | 447 | |
| | 448 | $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1; |
| | 449 | |
| | 450 | sub _make_unsupported_method { |
| | 451 | my ($pkg, $method, $type) = @_; |
| | 452 | |
| | 453 | local $^W; |
| | 454 | no strict qw(refs); |
| | 455 | |
| | 456 | *{"$pkg\::$method"} = sub { |
| | 457 | local $^W; |
| | 458 | if (defined $_[1] ? $_[1] : 1) { |
| | 459 | ${$_[0]} |= $type; |
| | 460 | } |
| | 461 | else { |
| | 462 | ${$_[0]} &= ~$type; |
| | 463 | } |
| | 464 | |
| | 465 | if (${$_[0]}) { |
| | 466 | *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode; |
| | 467 | *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode; |
| | 468 | } |
| | 469 | else { |
| | 470 | *JSON::XS::encode = $JSON_XS_encode_orignal; |
| | 471 | *JSON::XS::decode = $JSON_XS_decode_orignal; |
| | 472 | } |
| | 473 | |
| | 474 | $_[0]; |
| | 475 | }; |
| | 476 | |
| | 477 | *{"$pkg\::get_$method"} = sub { |
| | 478 | ${$_[0]} & $type ? 1 : ''; |
| | 479 | }; |
| | 480 | |
| | 481 | } |
| | 482 | |
| | 483 | |
| | 484 | sub _set_for_pp { |
| | 485 | require JSON::PP; |
| | 486 | my $type = shift; |
| | 487 | my $pp = new JSON::PP; |
| | 488 | my $prop = $_[0]->property; |
| | 489 | |
| | 490 | for my $name (keys %$prop) { |
| | 491 | $pp->$name( $prop->{$name} ? $prop->{$name} : 0 ); |
| | 492 | } |
| | 493 | |
| | 494 | my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG |
| | 495 | : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG; |
| | 496 | my $flags = ${$_[0]} || 0; |
| | 497 | |
| | 498 | for my $name (keys %$unsupported) { |
| | 499 | next if ($name eq 'EXPANDED'); # for developer's |
| | 500 | my $enable = ($flags & $unsupported->{$name}) ? 1 : 0; |
| | 501 | my $method = lc $name; |
| | 502 | $pp->$method($enable); |
| | 503 | } |
| | 504 | |
| | 505 | $pp->indent_length( $_[0]->get_indent_length ); |
| | 506 | |
| | 507 | return $pp; |
| | 508 | } |
| | 509 | |
| | 510 | |
| | 511 | sub _encode { # using with PP encod |
| | 512 | _set_for_pp('encode' => @_)->encode($_[1]); |
| | 513 | } |
| | 514 | |
| | 515 | |
| | 516 | sub _decode { # if unsupported-flag is set, use PP |
| | 517 | _set_for_pp('decode' => @_)->decode($_[1]); |
| | 518 | } |
| | 519 | |
| | 520 | |
| | 521 | sub decode_prefix { # if unsupported-flag is set, use PP |
| | 522 | _set_for_pp('decode' => @_)->decode_prefix($_[1]); |
| | 523 | } |
| | 524 | |
| | 525 | |
| | 526 | sub get_indent_length { |
| | 527 | ${$_[0]} << 4 >> 16; |
| | 528 | } |
| | 529 | |
| | 530 | |
| | 531 | sub indent_length { |
| | 532 | my $length = $_[1]; |
| | 533 | |
| | 534 | if (!defined $length or $length > 15 or $length < 0) { |
| | 535 | Carp::carp "The acceptable range of indent_length() is 0 to 15."; |
| | 536 | } |
| | 537 | else { |
| | 538 | local $^W; |
| | 539 | $length <<= 12; |
| | 540 | ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG; |
| | 541 | ${$_[0]} |= $length; |
| | 542 | *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode; |
| | 543 | } |
| | 544 | |
| | 545 | $_[0]; |
| | 546 | } |
| | 547 | |
| | 548 | |
| 190 | | This module converts between JSON (JavaScript Object Notation) and Perl |
| 191 | | data structure into each other. |
| 192 | | For JSON, See to http://www.crockford.com/JSON/. |
| 193 | | |
| 194 | | |
| 195 | | =head1 METHODS |
| | 596 | ************************** CAUTION ******************************** |
| | 597 | * This is 'JSON module version 2' and there are many differences * |
| | 598 | * to version 1.xx * |
| | 599 | * Please check your applications useing old version. * |
| | 600 | * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' * |
| | 601 | ******************************************************************* |
| | 602 | |
| | 603 | JSON (JavaScript Object Notation) is a simple data format. |
| | 604 | See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>). |
| | 605 | |
| | 606 | This module converts Perl data structures to JSON and vice versa using either |
| | 607 | L<JSON::XS> or L<JSON::PP>. |
| | 608 | |
| | 609 | JSON::XS is the fastest and most proper JSON module on CPAN which must be |
| | 610 | compiled and installed in your environment. |
| | 611 | JSON::PP is a pure-Perl module which is bundled in this distribution and |
| | 612 | has a strong compatibility to JSON::XS. |
| | 613 | |
| | 614 | This module try to use JSON::XS by default and fail to it, use JSON::PP instead. |
| | 615 | So its features completely depend on JSON::XS or JSON::PP. |
| | 616 | |
| | 617 | See to L<BACKEND MODULE DECISION>. |
| | 618 | |
| | 619 | To distinguish the module name 'JSON' and the format type JSON, |
| | 620 | the former is quoted by CE<lt>E<gt> (its results vary with your using media), |
| | 621 | and the latter is left just as it is. |
| | 622 | |
| | 623 | Module name : C<JSON> |
| | 624 | |
| | 625 | Format type : JSON |
| | 626 | |
| | 627 | =head2 FEATURES |
| | 628 | |
| | 629 | =over |
| | 630 | |
| | 631 | =item * correct unicode handling |
| | 632 | |
| | 633 | This module (i.e. backend modules) knows how to handle Unicode, documents |
| | 634 | how and when it does so, and even documents what "correct" means. |
| | 635 | |
| | 636 | Even though there are limitations, this feature is available since Perl version 5.6. |
| | 637 | |
| | 638 | JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions |
| | 639 | C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005. |
| | 640 | |
| | 641 | With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem, |
| | 642 | JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available. |
| | 643 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information. |
| | 644 | |
| | 645 | See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> |
| | 646 | and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>. |
| | 647 | |
| | 648 | |
| | 649 | =item * round-trip integrity |
| | 650 | |
| | 651 | When you serialise a perl data structure using only data types supported by JSON, |
| | 652 | the deserialised data structure is identical on the Perl level. |
| | 653 | (e.g. the string "2.0" doesn't suddenly become "2" just because it looks |
| | 654 | like a number). There minor I<are> exceptions to this, read the MAPPING |
| | 655 | section below to learn about those. |
| | 656 | |
| | 657 | =item * strict checking of JSON correctness |
| | 658 | |
| | 659 | There is no guessing, no generating of illegal JSON texts by default, |
| | 660 | and only JSON is accepted as input by default (the latter is a security |
| | 661 | feature). |
| | 662 | |
| | 663 | See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>. |
| | 664 | |
| | 665 | =item * fast |
| | 666 | |
| | 667 | This module returns a JSON::XS object itself if avaliable. |
| | 668 | Compared to other JSON modules and other serialisers such as Storable, |
| | 669 | JSON::XS usually compares favourably in terms of speed, too. |
| | 670 | |
| | 671 | If not avaliable, C<JSON> returns a JSON::PP object instead of JSON::XS and |
| | 672 | it is very slow as pure-Perl. |
| | 673 | |
| | 674 | =item * simple to use |
| | 675 | |
| | 676 | This module has both a simple functional interface as well as an |
| | 677 | object oriented interface interface. |
| | 678 | |
| | 679 | =item * reasonably versatile output formats |
| | 680 | |
| | 681 | You can choose between the most compact guaranteed-single-line format possible |
| | 682 | (nice for simple line-based protocols), a pure-ASCII format (for when your transport |
| | 683 | is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed |
| | 684 | format (for when you want to read that stuff). Or you can combine those features |
| | 685 | in whatever way you like. |
| | 686 | |
| | 687 | =back |
| | 688 | |
| | 689 | =head1 FUNCTIONAL INTERFACE |
| | 690 | |
| | 691 | Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>. |
| | 692 | C<to_json> and C<from_json> are additional functions. |
| | 693 | |
| | 694 | =head2 to_json |
| | 695 | |
| | 696 | $json_text = to_json($perl_scalar) |
| | 697 | |
| | 698 | Converts the given Perl data structure to a json string. |
| | 699 | |
| | 700 | This function call is functionally identical to: |
| | 701 | |
| | 702 | $json_text = JSON->new->encode($perl_scalar) |
| | 703 | |
| | 704 | Takes a hash reference as the second. |
| | 705 | |
| | 706 | $json_text = to_json($perl_scalar, $flag_hashref) |
| | 707 | |
| | 708 | So, |
| | 709 | |
| | 710 | $json_text = encode_json($perl_scalar, {utf8 => 1, pretty => 1}) |
| | 711 | |
| | 712 | equivalent to: |
| | 713 | |
| | 714 | $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar) |
| | 715 | |
| | 716 | |
| | 717 | =head2 from_json |
| | 718 | |
| | 719 | $perl_scalar = from_json($json_text) |
| | 720 | |
| | 721 | The opposite of C<to_json>: expects a json string and tries |
| | 722 | to parse it, returning the resulting reference. |
| | 723 | |
| | 724 | This function call is functionally identical to: |
| | 725 | |
| | 726 | $perl_scalar = JSON->decode($json_text) |
| | 727 | |
| | 728 | Takes a hash reference as the second. |
| | 729 | |
| | 730 | $perl_scalar = from_json($json_text, $flag_hashref) |
| | 731 | |
| | 732 | So, |
| | 733 | |
| | 734 | $perl_scalar = from_json($json_text, {utf8 => 1}) |
| | 735 | |
| | 736 | equivalent to: |
| | 737 | |
| | 738 | $perl_scalar = JSON->new->utf8(1)->decode($json_text) |
| | 739 | |
| | 740 | =head2 encode_json |
| | 741 | |
| | 742 | $json_text = encode_json $perl_scalar |
| | 743 | |
| | 744 | Converts the given Perl data structure to a UTF-8 encoded, binary string. |
| | 745 | |
| | 746 | This function call is functionally identical to: |
| | 747 | |
| | 748 | $json_text = JSON->new->utf8->encode($perl_scalar) |
| | 749 | |
| | 750 | =head2 decode_json |
| | 751 | |
| | 752 | $perl_scalar = decode_json $json_text |
| | 753 | |
| | 754 | The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries |
| | 755 | to parse that as an UTF-8 encoded JSON text, returning the resulting |
| | 756 | reference. |
| | 757 | |
| | 758 | This function call is functionally identical to: |
| | 759 | |
| | 760 | $perl_scalar = JSON->new->utf8->decode($json_text) |
| | 761 | |
| | 762 | =head2 JSON::is_bool |
| | 763 | |
| | 764 | $is_boolean = JSON::is_bool($scalar) |
| | 765 | |
| | 766 | Returns true if the passed scalar represents either JSON::true or |
| | 767 | JSON::false, two constants that act like C<1> and C<0> respectively |
| | 768 | and are also used to represent JSON C<true> and C<false> in Perl strings. |
| | 769 | |
| | 770 | =head2 JSON::true |
| | 771 | |
| | 772 | Returns JSON true value which is blessed object. |
| | 773 | It C<isa> JSON::Boolean object. |
| | 774 | |
| | 775 | =head2 JSON::false |
| | 776 | |
| | 777 | Returns JSON false value which is blessed object. |
| | 778 | It C<isa> JSON::Boolean object. |
| | 779 | |
| | 780 | =head2 JSON::null |
| | 781 | |
| | 782 | Returns C<undef>. |
| | 783 | |
| | 784 | See L<MAPPING>, below, for more information on how JSON values are mapped to |
| | 785 | Perl. |
| | 786 | |
| | 787 | =head1 COMMON OBJECT-ORIENTED INTERFACE |
| | 788 | |
| | 789 | |
| | 790 | =head2 new |
| | 791 | |
| | 792 | $json = new JSON |
| | 793 | |
| | 794 | Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP |
| | 795 | that can be used to de/encode JSON strings. |
| | 796 | |
| | 797 | All boolean flags described below are by default I<disabled>. |
| | 798 | |
| | 799 | The mutators for flags all return the JSON object again and thus calls can |
| | 800 | be chained: |
| | 801 | |
| | 802 | my $json = JSON->new->utf8->space_after->encode({a => [1,2]}) |
| | 803 | => {"a": [1, 2]} |
| | 804 | |
| | 805 | =head2 ascii |
| | 806 | |
| | 807 | $json = $json->ascii([$enable]) |
| | 808 | |
| | 809 | $enabled = $json->get_ascii |
| | 810 | |
| | 811 | If $enable is true (or missing), then the encode method will not generate characters outside |
| | 812 | the code range 0..127. Any Unicode characters outside that range will be escaped using either |
| | 813 | a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. |
| | 814 | |
| | 815 | If $enable is false, then the encode method will not escape Unicode characters unless |
| | 816 | required by the JSON syntax or other flags. This results in a faster and more compact format. |
| | 817 | |
| | 818 | This feature depends on the used Perl version and environment. |
| | 819 | |
| | 820 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP. |
| | 821 | |
| | 822 | JSON->new->ascii(1)->encode([chr 0x10401]) |
| | 823 | => ["\ud801\udc01"] |
| | 824 | |
| | 825 | =head2 latin1 |
| | 826 | |
| | 827 | $json = $json->latin1([$enable]) |
| | 828 | |
| | 829 | $enabled = $json->get_latin1 |
| | 830 | |
| | 831 | If $enable is true (or missing), then the encode method will encode the resulting JSON |
| | 832 | text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255. |
| | 833 | |
| | 834 | If $enable is false, then the encode method will not escape Unicode characters |
| | 835 | unless required by the JSON syntax or other flags. |
| | 836 | |
| | 837 | JSON->new->latin1->encode (["\x{89}\x{abc}"] |
| | 838 | => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) |
| | 839 | |
| | 840 | =head2 utf8 |
| | 841 | |
| | 842 | $json = $json->utf8([$enable]) |
| | 843 | |
| | 844 | $enabled = $json->get_utf8 |
| | 845 | |
| | 846 | If $enable is true (or missing), then the encode method will encode the JSON result |
| | 847 | into UTF-8, as required by many protocols, while the decode method expects to be handled |
| | 848 | an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any |
| | 849 | characters outside the range 0..255, they are thus useful for bytewise/binary I/O. |
| | 850 | |
| | 851 | In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 |
| | 852 | encoding families, as described in RFC4627. |
| | 853 | |
| | 854 | If $enable is false, then the encode method will return the JSON string as a (non-encoded) |
| | 855 | Unicode string, while decode expects thus a Unicode string. Any decoding or encoding |
| | 856 | (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module. |
| | 857 | |
| | 858 | |
| | 859 | Example, output UTF-16BE-encoded JSON: |
| | 860 | |
| | 861 | use Encode; |
| | 862 | $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); |
| | 863 | |
| | 864 | Example, decode UTF-32LE-encoded JSON: |
| | 865 | |
| | 866 | use Encode; |
| | 867 | $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); |
| | 868 | |
| | 869 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP. |
| | 870 | |
| | 871 | |
| | 872 | =head2 pretty |
| | 873 | |
| | 874 | $json = $json->pretty([$enable]) |
| | 875 | |
| | 876 | This enables (or disables) all of the C<indent>, C<space_before> and |
| | 877 | C<space_after> (and in the future possibly more) flags in one call to |
| | 878 | generate the most readable (or most compact) form possible. |
| | 879 | |
| | 880 | Equivalent to: |
| | 881 | |
| | 882 | $json->indent->space_before->space_after |
| | 883 | |
| | 884 | The indent space length is three and JSON::XS cannot change the indent |
| | 885 | space length. |
| | 886 | |
| | 887 | =head2 indent |
| | 888 | |
| | 889 | $json = $json->indent([$enable]) |
| | 890 | |
| | 891 | $enabled = $json->get_indent |
| | 892 | |
| | 893 | If C<$enable> is true (or missing), then the C<encode> method will use a multiline |
| | 894 | format as output, putting every array member or object/hash key-value pair |
| | 895 | into its own line, identing them properly. |
| | 896 | |
| | 897 | If C<$enable> is false, no newlines or indenting will be produced, and the |
| | 898 | resulting JSON text is guarenteed not to contain any C<newlines>. |
| | 899 | |
| | 900 | This setting has no effect when decoding JSON texts. |
| | 901 | |
| | 902 | The indent space length is three. |
| | 903 | With JSON::PP, you can also access C<indent_length> to change indent space length. |
| | 904 | |
| | 905 | |
| | 906 | =head2 space_before |
| | 907 | |
| | 908 | $json = $json->space_before([$enable]) |
| | 909 | |
| | 910 | $enabled = $json->get_space_before |
| | 911 | |
| | 912 | If C<$enable> is true (or missing), then the C<encode> method will add an extra |
| | 913 | optional space before the C<:> separating keys from values in JSON objects. |
| | 914 | |
| | 915 | If C<$enable> is false, then the C<encode> method will not add any extra |
| | 916 | space at those places. |
| | 917 | |
| | 918 | This setting has no effect when decoding JSON texts. |
| | 919 | |
| | 920 | Example, space_before enabled, space_after and indent disabled: |
| | 921 | |
| | 922 | {"key" :"value"} |
| | 923 | |
| | 924 | |
| | 925 | =head2 space_after |
| | 926 | |
| | 927 | $json = $json->space_after([$enable]) |
| | 928 | |
| | 929 | $enabled = $json->get_space_after |
| | 930 | |
| | 931 | If C<$enable> is true (or missing), then the C<encode> method will add an extra |
| | 932 | optional space after the C<:> separating keys from values in JSON objects |
| | 933 | and extra whitespace after the C<,> separating key-value pairs and array |
| | 934 | members. |
| | 935 | |
| | 936 | If C<$enable> is false, then the C<encode> method will not add any extra |
| | 937 | space at those places. |
| | 938 | |
| | 939 | This setting has no effect when decoding JSON texts. |
| | 940 | |
| | 941 | Example, space_before and indent disabled, space_after enabled: |
| | 942 | |
| | 943 | {"key": "value"} |
| | 944 | |
| | 945 | |
| | 946 | =head2 relaxed |
| | 947 | |
| | 948 | $json = $json->relaxed([$enable]) |
| | 949 | |
| | 950 | $enabled = $json->get_relaxed |
| | 951 | |
| | 952 | If C<$enable> is true (or missing), then C<decode> will accept some |
| | 953 | extensions to normal JSON syntax (see below). C<encode> will not be |
| | 954 | affected in anyway. I<Be aware that this option makes you accept invalid |
| | 955 | JSON texts as if they were valid!>. I suggest only to use this option to |
| | 956 | parse application-specific files written by humans (configuration files, |
| | 957 | resource files etc.) |
| | 958 | |
| | 959 | If C<$enable> is false (the default), then C<decode> will only accept |
| | 960 | valid JSON texts. |
| | 961 | |
| | 962 | Currently accepted extensions are: |
| 199 | | =item new() |
| 200 | | |
| 201 | | =item new( %options ) |
| 202 | | |
| 203 | | returns a JSON object. The object delegates the converting and parsing process |
| 204 | | to L<JSON::Converter> and L<JSON::Parser>. |
| 205 | | |
| 206 | | my $json = new JSON; |
| 207 | | |
| 208 | | C<new> can take some options. |
| 209 | | |
| 210 | | my $json = new JSON (autoconv => 0, pretty => 1); |
| 211 | | |
| 212 | | Following options are supported: |
| | 966 | =item * list items can have an end-comma |
| | 967 | |
| | 968 | JSON I<separates> array elements and key-value pairs with commas. This |
| | 969 | can be annoying if you write JSON texts manually and want to be able to |
| | 970 | quickly append elements, so this extension accepts comma at the end of |
| | 971 | such items not just between them: |
| | 972 | |
| | 973 | [ |
| | 974 | 1, |
| | 975 | 2, <- this comma not normally allowed |
| | 976 | ] |
| | 977 | { |
| | 978 | "k1": "v1", |
| | 979 | "k2": "v2", <- this comma not normally allowed |
| | 980 | } |
| | 981 | |
| | 982 | =item * shell-style '#'-comments |
| | 983 | |
| | 984 | Whenever JSON allows whitespace, shell-style comments are additionally |
| | 985 | allowed. They are terminated by the first carriage-return or line-feed |
| | 986 | character, after which more white-space and comments are allowed. |
| | 987 | |
| | 988 | [ |
| | 989 | 1, # this comment not allowed in JSON |
| | 990 | # neither this one... |
| | 991 | ] |
| | 992 | |
| | 993 | =back |
| | 994 | |
| | 995 | |
| | 996 | =head2 canonical |
| | 997 | |
| | 998 | $json = $json->canonical([$enable]) |
| | 999 | |
| | 1000 | $enabled = $json->get_canonical |
| | 1001 | |
| | 1002 | If C<$enable> is true (or missing), then the C<encode> method will output JSON objects |
| | 1003 | by sorting their keys. This is adding a comparatively high overhead. |
| | 1004 | |
| | 1005 | If C<$enable> is false, then the C<encode> method will output key-value |
| | 1006 | pairs in the order Perl stores them (which will likely change between runs |
| | 1007 | of the same script). |
| | 1008 | |
| | 1009 | This option is useful if you want the same data structure to be encoded as |
| | 1010 | the same JSON text (given the same overall settings). If it is disabled, |
| | 1011 | the same hash might be encoded differently even if contains the same data, |
| | 1012 | as key-value pairs have no inherent ordering in Perl. |
| | 1013 | |
| | 1014 | This setting has no effect when decoding JSON texts. |
| | 1015 | |
| | 1016 | =head2 allow_nonref |
| | 1017 | |
| | 1018 | $json = $json->allow_nonref([$enable]) |
| | 1019 | |
| | 1020 | $enabled = $json->get_allow_nonref |
| | 1021 | |
| | 1022 | If C<$enable> is true (or missing), then the C<encode> method can convert a |
| | 1023 | non-reference into its corresponding string, number or null JSON value, |
| | 1024 | which is an extension to RFC4627. Likewise, C<decode> will accept those JSON |
| | 1025 | values instead of croaking. |
| | 1026 | |
| | 1027 | If C<$enable> is false, then the C<encode> method will croak if it isn't |
| | 1028 | passed an arrayref or hashref, as JSON texts must either be an object |
| | 1029 | or array. Likewise, C<decode> will croak if given something that is not a |
| | 1030 | JSON object or array. |
| | 1031 | |
| | 1032 | JSON->new->allow_nonref->encode ("Hello, World!") |
| | 1033 | => "Hello, World!" |
| | 1034 | |
| | 1035 | =head2 allow_unknown |
| | 1036 | |
| | 1037 | $json = $json->allow_unknown ([$enable]) |
| | 1038 | |
| | 1039 | $enabled = $json->get_allow_unknown |
| | 1040 | |
| | 1041 | If $enable is true (or missing), then "encode" will *not* throw an |
| | 1042 | exception when it encounters values it cannot represent in JSON (for |
| | 1043 | example, filehandles) but instead will encode a JSON "null" value. |
| | 1044 | Note that blessed objects are not included here and are handled |
| | 1045 | separately by c<allow_nonref>. |
| | 1046 | |
| | 1047 | If $enable is false (the default), then "encode" will throw an |
| | 1048 | exception when it encounters anything it cannot encode as JSON. |
| | 1049 | |
| | 1050 | This option does not affect "decode" in any way, and it is |
| | 1051 | recommended to leave it off unless you know your communications |
| | 1052 | partner. |
| | 1053 | |
| | 1054 | =head2 allow_blessed |
| | 1055 | |
| | 1056 | $json = $json->allow_blessed([$enable]) |
| | 1057 | |
| | 1058 | $enabled = $json->get_allow_blessed |
| | 1059 | |
| | 1060 | If C<$enable> is true (or missing), then the C<encode> method will not |
| | 1061 | barf when it encounters a blessed reference. Instead, the value of the |
| | 1062 | B<convert_blessed> option will decide whether C<null> (C<convert_blessed> |
| | 1063 | disabled or no C<TO_JSON> method found) or a representation of the |
| | 1064 | object (C<convert_blessed> enabled and C<TO_JSON> method found) is being |
| | 1065 | encoded. Has no effect on C<decode>. |
| | 1066 | |
| | 1067 | If C<$enable> is false (the default), then C<encode> will throw an |
| | 1068 | exception when it encounters a blessed object. |
| | 1069 | |
| | 1070 | |
| | 1071 | =head2 convert_blessed |
| | 1072 | |
| | 1073 | $json = $json->convert_blessed([$enable]) |
| | 1074 | |
| | 1075 | $enabled = $json->get_convert_blessed |
| | 1076 | |
| | 1077 | If C<$enable> is true (or missing), then C<encode>, upon encountering a |
| | 1078 | blessed object, will check for the availability of the C<TO_JSON> method |
| | 1079 | on the object's class. If found, it will be called in scalar context |
| | 1080 | and the resulting scalar will be encoded instead of the object. If no |
| | 1081 | C<TO_JSON> method is found, the value of C<allow_blessed> will decide what |
| | 1082 | to do. |
| | 1083 | |
| | 1084 | The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON> |
| | 1085 | returns other blessed objects, those will be handled in the same |
| | 1086 | way. C<TO_JSON> must take care of not causing an endless recursion cycle |
| | 1087 | (== crash) in this case. The name of C<TO_JSON> was chosen because other |
| | 1088 | methods called by the Perl core (== not by the user of the object) are |
| | 1089 | usually in upper case letters and to avoid collisions with the C<to_json> |
| | 1090 | function or method. |
| | 1091 | |
| | 1092 | This setting does not yet influence C<decode> in any way. |
| | 1093 | |
| | 1094 | If C<$enable> is false, then the C<allow_blessed> setting will decide what |
| | 1095 | to do when a blessed object is found. |
| | 1096 | |
| | 1097 | =over |
| | 1098 | |
| | 1099 | =item convert_blessed_universally mode |
| | 1100 | |
| | 1101 | If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON> |
| | 1102 | subroutine is defined as the below code: |
| | 1103 | |
| | 1104 | *UNIVERSAL::TO_JSON = sub { |
| | 1105 | my $b_obj = B::svref_2object( $_[0] ); |
| | 1106 | return $b_obj->isa('B::HV') ? { %{ $_[0] } } |
| | 1107 | : $b_obj->isa('B::AV') ? [ @{ $_[0] } ] |
| | 1108 | : undef |
| | 1109 | ; |
| | 1110 | } |
| | 1111 | |
| | 1112 | This will cause that C<encode> method converts simple blessed objects into |
| | 1113 | JSON objects as non-blessed object. |
| | 1114 | |
| | 1115 | JSON -convert_blessed_universally; |
| | 1116 | $json->allow_blessed->convert_blessed->encode( $blessed_object ) |
| | 1117 | |
| | 1118 | This feature is experimental and may be removed in the future. |
| | 1119 | |
| | 1120 | =back |
| | 1121 | |
| | 1122 | =head2 filter_json_object |
| | 1123 | |
| | 1124 | $json = $json->filter_json_object([$coderef]) |
| | 1125 | |
| | 1126 | When C<$coderef> is specified, it will be called from C<decode> each |
| | 1127 | time it decodes a JSON object. The only argument passed to the coderef |
| | 1128 | is a reference to the newly-created hash. If the code references returns |
| | 1129 | a single scalar (which need not be a reference), this value |
| | 1130 | (i.e. a copy of that scalar to avoid aliasing) is inserted into the |
| | 1131 | deserialised data structure. If it returns an empty list |
| | 1132 | (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised |
| | 1133 | hash will be inserted. This setting can slow down decoding considerably. |
| | 1134 | |
| | 1135 | When C<$coderef> is omitted or undefined, any existing callback will |
| | 1136 | be removed and C<decode> will not change the deserialised hash in any |
| | 1137 | way. |
| | 1138 | |
| | 1139 | Example, convert all JSON objects into the integer 5: |
| | 1140 | |
| | 1141 | my $js = JSON->new->filter_json_object (sub { 5 }); |
| | 1142 | # returns [5] |
| | 1143 | $js->decode ('[{}]'); # the given subroutine takes a hash reference. |
| | 1144 | # throw an exception because allow_nonref is not enabled |
| | 1145 | # so a lone 5 is not allowed. |
| | 1146 | $js->decode ('{"a":1, "b":2}'); |
| | 1147 | |
| | 1148 | |
| | 1149 | =head2 filter_json_single_key_object |
| | 1150 | |
| | 1151 | $json = $json->filter_json_single_key_object($key [=> $coderef]) |
| | 1152 | |
| | 1153 | Works remotely similar to C<filter_json_object>, but is only called for |
| | 1154 | JSON objects having a single key named C<$key>. |
| | 1155 | |
| | 1156 | This C<$coderef> is called before the one specified via |
| | 1157 | C<filter_json_object>, if any. It gets passed the single value in the JSON |
| | 1158 | object. If it returns a single value, it will be inserted into the data |
| | 1159 | structure. If it returns nothing (not even C<undef> but the empty list), |
| | 1160 | the callback from C<filter_json_object> will be called next, as if no |
| | 1161 | single-key callback were specified. |
| | 1162 | |
| | 1163 | If C<$coderef> is omitted or undefined, the corresponding callback will be |
| | 1164 | disabled. There can only ever be one callback for a given key. |
| | 1165 | |
| | 1166 | As this callback gets called less often then the C<filter_json_object> |
| | 1167 | one, decoding speed will not usually suffer as much. Therefore, single-key |
| | 1168 | objects make excellent targets to serialise Perl objects into, especially |
| | 1169 | as single-key JSON objects are as close to the type-tagged value concept |
| | 1170 | as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not |
| | 1171 | support this in any way, so you need to make sure your data never looks |
| | 1172 | like a serialised Perl hash. |
| | 1173 | |
| | 1174 | Typical names for the single object key are C<__class_whatever__>, or |
| | 1175 | C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even |
| | 1176 | things like C<__class_md5sum(classname)__>, to reduce the risk of clashing |
| | 1177 | with real hashes. |
| | 1178 | |
| | 1179 | Example, decode JSON objects of the form C<< { "__widget__" => <id> } >> |
| | 1180 | into the corresponding C<< $WIDGET{<id>} >> object: |
| | 1181 | |
| | 1182 | # return whatever is in $WIDGET{5}: |
| | 1183 | JSON |
| | 1184 | ->new |
| | 1185 | ->filter_json_single_key_object (__widget__ => sub { |
| | 1186 | $WIDGET{ $_[0] } |
| | 1187 | }) |
| | 1188 | ->decode ('{"__widget__": 5') |
| | 1189 | |
| | 1190 | # this can be used with a TO_JSON method in some "widget" class |
| | 1191 | # for serialisation to json: |
| | 1192 | sub WidgetBase::TO_JSON { |
| | 1193 | my ($self) = @_; |
| | 1194 | |
| | 1195 | unless ($self->{id}) { |
| | 1196 | $self->{id} = ..get..some..id..; |
| | 1197 | $WIDGET{$self->{id}} = $self; |
| | 1198 | } |
| | 1199 | |
| | 1200 | { __widget__ => $self->{id} } |
| | 1201 | } |
| | 1202 | |
| | 1203 | |
| | 1204 | =head2 shrink |
| | 1205 | |
| | 1206 | $json = $json->shrink([$enable]) |
| | 1207 | |
| | 1208 | $enabled = $json->get_shrink |
| | 1209 | |
| | 1210 | With JSON::XS, this flag resizes strings generated by either |
| | 1211 | C<encode> or C<decode> to their minimum size possible. This can save |
| | 1212 | memory when your JSON texts are either very very long or you have many |
| | 1213 | short strings. It will also try to downgrade any strings to octet-form |
| | 1214 | if possible: perl stores strings internally either in an encoding called |
| | 1215 | UTF-X or in octet-form. The latter cannot store everything but uses less |
| | 1216 | space in general (and some buggy Perl or C code might even rely on that |
| | 1217 | internal representation being used). |
| | 1218 | |
| | 1219 | With JSON::PP, it is noop about resizing strings but tries |
| | 1220 | C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>. |
| | 1221 | |
| | 1222 | See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>. |
| | 1223 | |
| | 1224 | =head2 max_depth |
| | 1225 | |
| | 1226 | $json = $json->max_depth([$maximum_nesting_depth]) |
| | 1227 | |
| | 1228 | $max_depth = $json->get_max_depth |
| | 1229 | |
| | 1230 | Sets the maximum nesting level (default C<512>) accepted while encoding |
| | 1231 | or decoding. If a higher nesting level is detected in JSON text or a Perl |
| | 1232 | data structure, then the encoder and decoder will stop and croak at that |
| | 1233 | point. |
| | 1234 | |
| | 1235 | Nesting level is defined by number of hash- or arrayrefs that the encoder |
| | 1236 | needs to traverse to reach a given point or the number of C<{> or C<[> |
| | 1237 | characters without their matching closing parenthesis crossed to reach a |
| | 1238 | given character in a string. |
| | 1239 | |
| | 1240 | If no argument is given, the highest possible setting will be used, which |
| | 1241 | is rarely useful. |
| | 1242 | |
| | 1243 | Note that nesting is implemented by recursion in C. The default value has |
| | 1244 | been chosen to be as large as typical operating systems allow without |
| | 1245 | crashing. (JSON::XS) |
| | 1246 | |
| | 1247 | With JSON::PP as the backend, when a large value (100 or more) was set and |
| | 1248 | it de/encodes a deep nested object/text, it may raise a warning |
| | 1249 | 'Deep recursion on subroutin' at the perl runtime phase. |
| | 1250 | |
| | 1251 | See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful. |
| | 1252 | |
| | 1253 | =head2 max_size |
| | 1254 | |
| | 1255 | $json = $json->max_size([$maximum_string_size]) |
| | 1256 | |
| | 1257 | $max_size = $json->get_max_size |
| | 1258 | |
| | 1259 | Set the maximum length a JSON text may have (in bytes) where decoding is |
| | 1260 | being attempted. The default is C<0>, meaning no limit. When C<decode> |
| | 1261 | is called on a string that is longer then this many bytes, it will not |
| | 1262 | attempt to decode the string but throw an exception. This setting has no |
| | 1263 | effect on C<encode> (yet). |
| | 1264 | |
| | 1265 | If no argument is given, the limit check will be deactivated (same as when |
| | 1266 | C<0> is specified). |
| | 1267 | |
| | 1268 | See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful. |
| | 1269 | |
| | 1270 | =head2 encode |
| | 1271 | |
| | 1272 | $json_text = $json->encode($perl_scalar) |
| | 1273 | |
| | 1274 | Converts the given Perl data structure (a simple scalar or a reference |
| | 1275 | to a hash or array) to its JSON representation. Simple scalars will be |
| | 1276 | converted into JSON string or number sequences, while references to arrays |
| | 1277 | become JSON arrays and references to hashes become JSON objects. Undefined |
| | 1278 | Perl values (e.g. C<undef>) become JSON C<null> values. Neither C<true> |
| | 1279 | nor C<false> values will be generated. |
| | 1280 | |
| | 1281 | =head2 decode |
| | 1282 | |
| | 1283 | $perl_scalar = $json->decode($json_text) |
| | 1284 | |
| | 1285 | The opposite of C<encode>: expects a JSON text and tries to parse it, |
| | 1286 | returning the resulting simple scalar or reference. Croaks on error. |
| | 1287 | |
| | 1288 | JSON numbers and strings become simple Perl scalars. JSON arrays become |
| | 1289 | Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes |
| | 1290 | C<1>, C<false> becomes C<0> and C<null> becomes C<undef>. |
| | 1291 | |
| | 1292 | =head2 decode_prefix |
| | 1293 | |
| | 1294 | ($perl_scalar, $characters) = $json->decode_prefix($json_text) |
| | 1295 | |
| | 1296 | This works like the C<decode> method, but instead of raising an exception |
| | 1297 | when there is trailing garbage after the first JSON object, it will |
| | 1298 | silently stop parsing there and return the number of characters consumed |
| | 1299 | so far. |
| | 1300 | |
| | 1301 | JSON->new->decode_prefix ("[1] the tail") |
| | 1302 | => ([], 3) |
| | 1303 | |
| | 1304 | See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> |
| | 1305 | |
| | 1306 | =head2 property |
| | 1307 | |
| | 1308 | $boolean = $json->property($property_name) |
| | 1309 | |
| | 1310 | Returns a boolean value about above some properties. |
| | 1311 | |
| | 1312 | The available properties are C<ascii>, C<latin1>, C<utf8>, |
| | 1313 | C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>, |
| | 1314 | C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>, |
| | 1315 | C<shrink>, C<max_depth> and C<max_size>. |
| | 1316 | |
| | 1317 | $boolean = $json->property('utf8'); |
| | 1318 | => 0 |
| | 1319 | $json->utf8; |
| | 1320 | $boolean = $json->property('utf8'); |
| | 1321 | => 1 |
| | 1322 | |
| | 1323 | Sets the propery with a given boolean value. |
| | 1324 | |
| | 1325 | $json = $json->property($property_name => $boolean); |
| | 1326 | |
| | 1327 | With no argumnt, it returns all the above properties as a hash reference. |
| | 1328 | |
| | 1329 | $flag_hashref = $json->property(); |
| | 1330 | |
| | 1331 | =head1 INCREMENTAL PARSING |
| | 1332 | |
| | 1333 | In JSON::XS 2.2, incremental parsing feature of JSON texts was implemented. |
| | 1334 | Please check to L<JSON::XS/INCREMENTAL PARSING>. |
| 216 | | =item autoconv |
| 217 | | |
| 218 | | See L</AUTOCONVERT> for more info. |
| 219 | | |
| 220 | | =item skipinvalid |
| 221 | | |
| 222 | | C<objToJson()> does C<die()> when it encounters any invalid data |
| 223 | | (for instance, coderefs). If C<skipinvalid> is set with true, |
| 224 | | the function convets these invalid data into JSON format's C<null>. |
| 225 | | |
| 226 | | =item execcoderef |
| 227 | | |
| 228 | | C<objToJson()> does C<die()> when it encounters any code reference. |
| 229 | | However, if C<execcoderef> is set with true, executes the coderef |
| 230 | | and uses returned value. |
| 231 | | |
| 232 | | =item pretty |
| 233 | | |
| 234 | | See L</PRETY PRINTING> for more info. |
| 235 | | |
| 236 | | =item indent |
| 237 | | |
| 238 | | See L</PRETY PRINTING> for more info. |
| 239 | | |
| 240 | | =item delimiter |
| 241 | | |
| 242 | | See L</PRETY PRINTING> for more info. |
| 243 | | |
| 244 | | =back |
| 245 | | |
| 246 | | |
| 247 | | =item objToJson( $object ) |
| 248 | | |
| 249 | | =item objToJson( $object, $hashref ) |
| 250 | | |
| 251 | | takes perl data structure (basically, they are scalars, arrayrefs and hashrefs) |
| 252 | | and returns JSON formated string. |
| 253 | | |
| 254 | | my $obj = [1, 2, {foo => bar}]; |
| 255 | | my $js = $json->objToJson($obj); |
| 256 | | # [1,2,{"foo":"bar"}] |
| 257 | | |
| 258 | | By default, returned string is one-line. However, you can get pretty-printed |
| 259 | | data with C<pretty> option. Please see below L</PRETY PRINTING>. |
| 260 | | |
| 261 | | my $js = $json->objToJson($obj, {pretty => 1, indent => 2}); |
| 262 | | # [ |
| 263 | | # 1, |
| 264 | | # 2, |
| 265 | | # { |
| 266 | | # "foo" : "bar" |
| 267 | | # } |
| 268 | | # ] |
| 269 | | |
| 270 | | =item jsonToObj( $js ) |
| 271 | | |
| 272 | | takes a JSON formated data and returns a perl data structure. |
| 273 | | |
| 274 | | |
| 275 | | =item autoconv() |
| 276 | | |
| 277 | | =item autoconv($bool) |
| 278 | | |
| 279 | | This is an accessor to C<autoconv>. See L</AUTOCONVERT> for more info. |
| 280 | | |
| 281 | | =item pretty() |
| 282 | | |
| 283 | | =item pretty($bool) |
| 284 | | |
| 285 | | This is an accessor to C<pretty>. It takes true or false. |
| 286 | | When prrety is true, C<objToJson()> returns prrety-printed string. |
| 287 | | See L</PRETY PRINTING> for more info. |
| 288 | | |
| 289 | | =item indent() |
| 290 | | |
| 291 | | =item indent($integer) |
| 292 | | |
| 293 | | This is an accessor to C<indent>. |
| 294 | | See L</PRETY PRINTING> for more info. |
| 295 | | |
| 296 | | =item delimiter() |
| 297 | | |
| 298 | | This is an accessor to C<delimiter>. |
| 299 | | See L</PRETY PRINTING> for more info. |
| 300 | | |
| | 1338 | =item [void, scalar or list context] = $json->incr_parse ([$string]) |
| | 1339 | |
| | 1340 | This is the central parsing function. It can both append new text and |
| | 1341 | extract objects from the stream accumulated so far (both of these |
| | 1342 | functions are optional). |
| | 1343 | |
| | 1344 | If C<$string> is given, then this string is appended to the already |
| | 1345 | existing JSON fragment stored in the C<$json> object. |
| | 1346 | |
| | 1347 | After that, if the function is called in void context, it will simply |
| | 1348 | return without doing anything further. This can be used to add more text |
| | 1349 | in as many chunks as you want. |
| | 1350 | |
| | 1351 | If the method is called in scalar context, then it will try to extract |
| | 1352 | exactly I<one> JSON object. If that is successful, it will return this |
| | 1353 | object, otherwise it will return C<undef>. If there is a parse error, |
| | 1354 | this method will croak just as C<decode> would do (one can then use |
| | 1355 | C<incr_skip> to skip the errornous part). This is the most common way of |
| | 1356 | using the method. |
| | 1357 | |
| | 1358 | And finally, in list context, it will try to extract as many objects |
| | 1359 | from the stream as it can find and return them, or the empty list |
| | 1360 | otherwise. For this to work, there must be no separators between the JSON |
| | 1361 | objects or arrays, instead they must be concatenated back-to-back. If |
| | 1362 | an error occurs, an exception will be raised as in the scalar context |
| | 1363 | case. Note that in this case, any previously-parsed JSON texts will be |
| | 1364 | lost. |
| | 1365 | |
| | 1366 | =item $lvalue_string = $json->incr_text |
| | 1367 | |
| | 1368 | This method returns the currently stored JSON fragment as an lvalue, that |
| | 1369 | is, you can manipulate it. This I<only> works when a preceding call to |
| | 1370 | C<incr_parse> in I<scalar context> successfully returned an object. Under |
| | 1371 | all other circumstances you must not call this function (I mean it. |
| | 1372 | although in simple tests it might actually work, it I<will> fail under |
| | 1373 | real world conditions). As a special exception, you can also call this |
| | 1374 | method before having parsed anything. |
| | 1375 | |
| | 1376 | This function is useful in two cases: a) finding the trailing text after a |
| | 1377 | JSON object or b) parsing multiple JSON objects separated by non-JSON text |
| | 1378 | (such as commas). |
| | 1379 | |
| | 1380 | In Perl 5.005, C<lvalue> attribute is not available. |
| | 1381 | You must write codes like the below: |
| | 1382 | |
| | 1383 | $string = $json->incr_text; |
| | 1384 | $string =~ s/\s*,\s*//; |
| | 1385 | $json->incr_text( $string ); |
| | 1386 | |
| | 1387 | =item $json->incr_skip |
| | 1388 | |
| | 1389 | This will reset the state of the incremental parser and will remove the |
| | 1390 | parsed text from the input buffer. This is useful after C<incr_parse> |
| | 1391 | died, in which case the input buffer and incremental parser state is left |
| | 1392 | unchanged, to skip the text parsed so far and to reset the parse state. |
| | 1393 | |
| | 1394 | =item $json->incr_reset |
| | 1395 | |
| | 1396 | This completely resets the incremental parser, that is, after this call, |
| | 1397 | it will be as if the parser had never parsed anything. |
| | 1398 | |
| | 1399 | This is useful if you want ot repeatedly parse JSON objects and want to |
| | 1400 | ignore any trailing data, which means you have to reset the parser after |
| | 1401 | each successful decode. |
| | 1405 | =head1 JSON::PP SUPPORT METHODS |
| | 1406 | |
| | 1407 | The below methods are JSON::PP own methods, so when C<JSON> works |
| | 1408 | with JSON::PP (i.e. the created object is a JSON::PP object), available. |
| | 1409 | See to L<JSON::PP/JSON::PP OWN METHODS> in detail. |
| | 1410 | |
| | 1411 | If you use C<JSON> with additonal C<-support_by_pp>, some methods |
| | 1412 | are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>. |
| | 1413 | |
| | 1414 | BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' } |
| | 1415 | |
| | 1416 | use JSON -support_by_pp; |
| | 1417 | |
| | 1418 | my $json = new JSON; |
| | 1419 | $json->allow_nonref->escape_slash->encode("/"); |
| | 1420 | |
| | 1421 | # functional interfaces too. |
| | 1422 | print to_json(["/"], {escape_slash => 1}); |
| | 1423 | print from_json('["foo"]', {utf8 => 1}); |
| | 1424 | |
| | 1425 | If you do not want to all functions but C<-support_by_pp>, |
| | 1426 | use C<-no_export>. |
| | 1427 | |
| | 1428 | use JSON -support_by_pp, -no_export; |
| | 1429 | # functional interfaces are not exported. |
| | 1430 | |
| | 1431 | =head2 allow_singlequote |
| | 1432 | |
| | 1433 | $json = $json->allow_singlequote([$enable]) |
| | 1434 | |
| | 1435 | If C<$enable> is true (or missing), then C<decode> will accept |
| | 1436 | any JSON strings quoted by single quotations that are invalid JSON |
| | 1437 | format. |
| | 1438 | |
| | 1439 | $json->allow_singlequote->decode({"foo":'bar'}); |
| | 1440 | $json->allow_singlequote->decode({'foo':"bar"}); |
| | 1441 | $json->allow_singlequote->decode({'foo':'bar'}); |
| | 1442 | |
| | 1443 | As same as the C<relaxed> option, this option may be used to parse |
| | 1444 | application-specific files written by humans. |
| | 1445 | |
| | 1446 | =head2 allow_barekey |
| | 1447 | |
| | 1448 | $json = $json->allow_barekey([$enable]) |
| | 1449 | |
| | 1450 | If C<$enable> is true (or missing), then C<decode> will accept |
| | 1451 | bare keys of JSON object that are invalid JSON format. |
| | 1452 | |
| | 1453 | As same as the C<relaxed> option, this option may be used to parse |
| | 1454 | application-specific files written by humans. |
| | 1455 | |
| | 1456 | $json->allow_barekey->decode('{foo:"bar"}'); |
| | 1457 | |
| | 1458 | =head2 allow_bignum |
| | 1459 | |
| | 1460 | $json = $json->allow_bignum([$enable]) |
| | 1461 | |
| | 1462 | If C<$enable> is true (or missing), then C<decode> will convert |
| | 1463 | the big integer Perl cannot handle as integer into a L<Math::BigInt> |
| | 1464 | object and convert a floating number (any) into a L<Math::BigFloat>. |
| | 1465 | |
| | 1466 | On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat> |
| | 1467 | objects into JSON numbers with C<allow_blessed> enable. |
| | 1468 | |
| | 1469 | $json->allow_nonref->allow_blessed->allow_bignum; |
| | 1470 | $bigfloat = $json->decode('2.000000000000000000000000001'); |
| | 1471 | print $json->encode($bigfloat); |
| | 1472 | # => 2.000000000000000000000000001 |
| | 1473 | |
| | 1474 | See to L<MAPPING> aboout the conversion of JSON number. |
| | 1475 | |
| | 1476 | =head2 loose |
| | 1477 | |
| | 1478 | $json = $json->loose([$enable]) |
| | 1479 | |
| | 1480 | The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings |
| | 1481 | and the module doesn't allow to C<decode> to these (except for \x2f). |
| | 1482 | If C<$enable> is true (or missing), then C<decode> will accept these |
| | 1483 | unescaped strings. |
| | 1484 | |
| | 1485 | $json->loose->decode(qq|["abc |
| | 1486 | def"]|); |
| | 1487 | |
| | 1488 | See to L<JSON::PP/JSON::PP OWN METHODS>. |
| | 1489 | |
| | 1490 | =head2 escape_slash |
| | 1491 | |
| | 1492 | $json = $json->escape_slash([$enable]) |
| | 1493 | |
| | 1494 | According to JSON Grammar, I<slash> (U+002F) is escaped. But by default |
| | 1495 | JSON backend modules encode strings without escaping slash. |
| | 1496 | |
| | 1497 | If C<$enable> is true (or missing), then C<encode> will escape slashes. |
| | 1498 | |
| | 1499 | =head2 indent_length |
| | 1500 | |
| | 1501 | $json = $json->indent_length($length) |
| | 1502 | |
| | 1503 | With JSON::XS, The indent space length is 3 and cannot be changed. |
| | 1504 | With JSON::PP, it sets the indent space length with the given $length. |
| | 1505 | The default is 3. The acceptable range is 0 to 15. |
| | 1506 | |
| | 1507 | =head2 sort_by |
| | 1508 | |
| | 1509 | $json = $json->sort_by($function_name) |
| | 1510 | $json = $json->sort_by($subroutine_ref) |
| | 1511 | |
| | 1512 | If $function_name or $subroutine_ref are set, its sort routine are used. |
| | 1513 | |
| | 1514 | $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj); |
| | 1515 | # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); |
| | 1516 | |
| | 1517 | $js = $pc->sort_by('own_sort')->encode($obj); |
| | 1518 | # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); |
| | 1519 | |
| | 1520 | sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b } |
| | 1521 | |
| | 1522 | As the sorting routine runs in the JSON::PP scope, the given |
| | 1523 | subroutine name and the special variables C<$a>, C<$b> will begin |
| | 1524 | with 'JSON::PP::'. |
| | 1525 | |
| | 1526 | If $integer is set, then the effect is same as C<canonical> on. |
| | 1527 | |
| | 1528 | See to L<JSON::PP/JSON::PP OWN METHODS>. |
| | 1529 | |
| 306 | | (JSON) {"param" : []} |
| 307 | | ( => Perl) {'param' => []}; |
| | 1532 | This section is copied from JSON::XS and modified to C<JSON>. |
| | 1533 | JSON::XS and JSON::PP mapping mechanisms are almost equivalent. |
| | 1534 | |
| | 1535 | See to L<JSON::XS/MAPPING>. |
| | 1536 | |
| | 1537 | =head2 JSON -> PERL |
| | 1538 | |
| | 1539 | =over 4 |
| | 1540 | |
| | 1541 | =item object |
| | 1542 | |
| | 1543 | A JSON object becomes a reference to a hash in Perl. No ordering of object |
| | 1544 | keys is preserved (JSON does not preserver object key ordering itself). |
| | 1545 | |
| | 1546 | =item array |
| | 1547 | |
| | 1548 | A JSON array becomes a reference to an array in Perl. |
| | 1549 | |
| | 1550 | =item string |
| | 1551 | |
| | 1552 | A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON |
| | 1553 | are represented by the same codepoints in the Perl string, so no manual |
| | 1554 | decoding is necessary. |
| | 1555 | |
| | 1556 | =item number |
| | 1557 | |
| | 1558 | A JSON number becomes either an integer, numeric (floating point) or |
| | 1559 | string scalar in perl, depending on its range and any fractional parts. On |
| | 1560 | the Perl level, there is no difference between those as Perl handles all |
| | 1561 | the conversion details, but an integer may take slightly less memory and |
| | 1562 | might represent more values exactly than floating point numbers. |
| | 1563 | |
| | 1564 | If the number consists of digits only, C<JSON> will try to represent |
| | 1565 | it as an integer value. If that fails, it will try to represent it as |
| | 1566 | a numeric (floating point) value if that is possible without loss of |
| | 1567 | precision. Otherwise it will preserve the number as a string value (in |
| | 1568 | which case you lose roundtripping ability, as the JSON number will be |
| | 1569 | re-encoded toa JSON string). |
| | 1570 | |
| | 1571 | Numbers containing a fractional or exponential part will always be |
| | 1572 | represented as numeric (floating point) values, possibly at a loss of |
| | 1573 | precision (in which case you might lose perfect roundtripping ability, but |
| | 1574 | the JSON number will still be re-encoded as a JSON number). |
| | 1575 | |
| | 1576 | If the backend is JSON::PP and C<allow_bignum> is enable, the big integers |
| | 1577 | and the numeric can be optionally converted into L<Math::BigInt> and |
| | 1578 | L<Math::BigFloat> objects. |
| | 1579 | |
| | 1580 | =item true, false |
| | 1581 | |
| | 1582 | These JSON atoms become C<JSON::true> and C<JSON::false>, |
| | 1583 | respectively. They are overloaded to act almost exactly like the numbers |
| | 1584 | C<1> and C<0>. You can check wether a scalar is a JSON boolean by using |
| | 1585 | the C<JSON::is_bool> function. |
| | 1586 | |
| | 1587 | If C<JSON::true> and C<JSON::false> are used as strings or compared as strings, |
| | 1588 | they represent as C<true> and C<false> respectively. |
| | 1589 | |
| | 1590 | print JSON::true . "\n"; |
| | 1591 | => true |
| | 1592 | print JSON::true + 1; |
| | 1593 | => 1 |
| | 1594 | |
| | 1595 | ok(JSON::true eq 'true'); |
| | 1596 | ok(JSON::true eq '1'); |
| | 1597 | ok(JSON::true == 1); |
| | 1598 | |
| | 1599 | C<JSON> will install these missing overloading features to the backend modules. |
| | 1600 | |
| | 1601 | |
| | 1602 | =item null |
| | 1603 | |
| | 1604 | A JSON null atom becomes C<undef> in Perl. |
| | 1605 | |
| | 1606 | C<JSON::null> returns C<unddef>. |
| | 1607 | |
| | 1608 | =back |
| | 1609 | |
| | 1610 | |
| | 1611 | =head2 PERL -> JSON |
| | 1612 | |
| | 1613 | The mapping from Perl to JSON is slightly more difficult, as Perl is a |
| | 1614 | truly typeless language, so we can only guess which JSON type is meant by |
| | 1615 | a Perl value. |
| | 1616 | |
| | 1617 | =over 4 |
| | 1618 | |
| | 1619 | =item hash references |
| | 1620 | |
| | 1621 | Perl hash references become JSON objects. As there is no inherent ordering |
| | 1622 | in hash keys (or JSON objects), they will usually be encoded in a |
| | 1623 | pseudo-random order that can change between runs of the same program but |
| | 1624 | stays generally the same within a single run of a program. C<JSON> |
| | 1625 | optionally sort the hash keys (determined by the I<canonical> flag), so |
| | 1626 | the same datastructure will serialise to the same JSON text (given same |
| | 1627 | settings and version of JSON::XS), but this incurs a runtime overhead |
| | 1628 | and is only rarely useful, e.g. when you want to compare some JSON text |
| | 1629 | against another for equality. |
| | 1630 | |
| | 1631 | In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism. |
| | 1632 | |
| | 1633 | |
| | 1634 | =item array references |
| | 1635 | |
| | 1636 | Perl array references become JSON arrays. |
| | 1637 | |
| | 1638 | =item other references |
| | 1639 | |
| | 1640 | Other unblessed references are generally not allowed and will cause an |
| | 1641 | exception to be thrown, except for references to the integers C<0> and |
| | 1642 | C<1>, which get turned into C<false> and C<true> atoms in JSON. You can |
| | 1643 | also use C<JSON::false> and C<JSON::true> to improve readability. |
| | 1644 | |
| | 1645 | to_json [\0,JSON::true] # yields [false,true] |
| | 1646 | |
| | 1647 | =item JSON::true, JSON::false, JSON::null |
| | 1648 | |
| | 1649 | These special values become JSON true and JSON false values, |
| | 1650 | respectively. You can also use C<\1> and C<\0> directly if you want. |
| | 1651 | |
| | 1652 | JSON::null returns C<undef>. |
| | 1653 | |
| | 1654 | =item blessed objects |
| | 1655 | |
| | 1656 | Blessed objects are not directly representable in JSON. See the |
| | 1657 | C<allow_blessed> and C<convert_blessed> methods on various options on |
| | 1658 | how to deal with this: basically, you can choose between throwing an |
| | 1659 | exception, encoding the reference as if it weren't blessed, or provide |
| | 1660 | your own serialiser method. |
| | 1661 | |
| | 1662 | With C<convert_blessed_universally> mode, C<encode> converts blessed |
| | 1663 | hash references or blessed array references (contains other blessed references) |
| | 1664 | into JSON members and arrays. |
| | 1665 | |
| | 1666 | use JSON -convert_blessed_universally; |
| | 1667 | JSON->new->allow_blessed->convert_blessed->encode( $blessed_object ); |
| | 1668 | |
| | 1669 | See to L<convert_blessed>. |
| | 1670 | |
| | 1671 | =item simple scalars |
| | 1672 | |
| | 1673 | Simple Perl scalars (any scalar that is not a reference) are the most |
| | 1674 | difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as |
| | 1675 | JSON C<null> values, scalars that have last been used in a string context |
| | 1676 | before encoding as JSON strings, and anything else as number value: |
| | 1677 | |
| | 1678 | # dump as number |
| | 1679 | encode_json [2] # yields [2] |
| | 1680 | encode_json [-3.0e17] # yields [-3e+17] |
| | 1681 | my $value = 5; encode_json [$value] # yields [5] |
| | 1682 | |
| | 1683 | # used as string, so dump as string |
| | 1684 | print $value; |
| | 1685 | encode_json [$value] # yields ["5"] |
| | 1686 | |
| | 1687 | # undef becomes null |
| | 1688 | encode_json [undef] # yields [null] |
| | 1689 | |
| | 1690 | You can force the type to be a string by stringifying it: |
| | 1691 | |
| | 1692 | my $x = 3.1; # some variable containing a number |
| | 1693 | "$x"; # stringified |
| | 1694 | $x .= ""; # another, more awkward way to stringify |
| | 1695 | print $x; # perl does it for you, too, quite often |
| | 1696 | |
| | 1697 | You can force the type to be a number by numifying it: |
| | 1698 | |
| | 1699 | my $x = "3"; # some variable containing a string |
| | 1700 | $x += 0; # numify it, ensuring it will be dumped as a number |
| | 1701 | $x *= 1; # same thing, the choise is yours. |
| | 1702 | |
| | 1703 | You can not currently force the type in other, less obscure, ways. |
| | 1704 | |
| | 1705 | =item Big Number |
| | 1706 | |
| | 1707 | If the backend is JSON::PP and C<allow_bignum> is enable, |
| | 1708 | C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat> |
| | 1709 | objects into JSON numbers. |
| | 1710 | |
| | 1711 | |
| | 1712 | =back |
| | 1713 | |
| | 1714 | =head1 JSON and YAML |
| | 1715 | |
| | 1716 | JSON is not a subset of YAML. |
| | 1717 | See to L<JSON::XS/JSON and YAML>. |
| | 1718 | |
| | 1719 | |
| | 1720 | =head1 BACKEND MODULE DECISION |
| | 1721 | |
| | 1722 | When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will |
| | 1723 | C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later. |
| | 1724 | |
| | 1725 | The C<JSON> constructor method returns an object inherited from the backend module, |
| | 1726 | and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash |
| | 1727 | reference. |
| | 1728 | |
| | 1729 | So, your program should not depend on the backend module, especially |
| | 1730 | returned objects should not be modified. |
| | 1731 | |
| | 1732 | my $json = JSON->new; # XS or PP? |
| | 1733 | $json->{stash} = 'this is xs object'; # this code may raise an error! |
| | 1734 | |
| | 1735 | To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>. |
| | 1736 | |
| | 1737 | JSON->backend; # 'JSON::XS' or 'JSON::PP' |
| | 1738 | |
| | 1739 | JSON->backend->is_pp: # 0 or 1 |
| | 1740 | |
| | 1741 | JSON->backend->is_xs: # 1 or 0 |
| | 1742 | |
| | 1743 | $json->is_xs; # 1 or 0 |
| | 1744 | |
| | 1745 | $json->is_pp; # 0 or 1 |
| | 1746 | |
| | 1747 | |
| | 1748 | If you set an enviornment variable C<PERL_JSON_BACKEND>, The calling action will be changed. |
| | 1749 | |
| | 1750 | =over |
| | 1751 | |
| | 1752 | =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP' |
| | 1753 | |
| | 1754 | Always use JSON::PP |
| | 1755 | |
| | 1756 | =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP' |
| | 1757 | |
| | 1758 | (The default) Use compiled JSON::XS if it is properly compiled & installed, |
| | 1759 | otherwise use JSON::PP. |
| | 1760 | |
| | 1761 | =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS' |
| | 1762 | |
| | 1763 | Always use compiled JSON::XS, die if it isn't properly compiled & installed. |
| | 1764 | |
| | 1765 | =back |
| | 1766 | |
| | 1767 | These ideas come from L<DBI::PurePerl> mechanism. |
| | 1768 | |
| | 1769 | example: |
| | 1770 | |
| | 1771 | BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' } |
| | 1772 | use JSON; # always uses JSON::PP |
| | 1773 | |
| | 1774 | In future, it may be able to specify another module. |
| | 1775 | |
| | 1776 | =head1 USE PP FEATURES EVEN THOUGH XS BACKEND |
| | 1777 | |
| | 1778 | Many methods are available with either JSON::XS or JSON::PP and |
| | 1779 | when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported) |
| | 1780 | method is called, it will C<warn> and be noop. |
| | 1781 | |
| | 1782 | But If you C<use> C<JSON> passing the optional string C<-support_by_pp>, |
| | 1783 | it makes a part of those unupported methods available. |
| | 1784 | This feature is achieved by using JSON::PP in C<de/encode>. |
| | 1785 | |
| | 1786 | BEING { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS |
| | 1787 | use JSON -support_by_pp; |
| | 1788 | my $json = new JSON; |
| | 1789 | $json->allow_nonref->escape_slash->encode("/"); |
| | 1790 | |
| | 1791 | At this time, the returned object is a C<JSON::Backend::XS::Supportable> |
| | 1792 | object (re-blessed XS object), and by checking JSON::XS unsupported flags |
| | 1793 | in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>, |
| | 1794 | C<allow_barekey>, C<allow_singlequote>, C<escape_slash>, C<as_nonblessed> |
| | 1795 | and C<indent_length>. |
| | 1796 | |
| | 1797 | When any unsupported methods are not enable, C<XS de/encode> will be |
| | 1798 | used as is. The switch is achieved by changing the symbolic tables. |
| | 1799 | |
| | 1800 | C<-support_by_pp> is effective only when the backend module is JSON::XS |
| | 1801 | and it makes the de/encoding speed down a bit. |
| | 1802 | |
| | 1803 | See to L<JSON::PP SUPPORT METHODS>. |
| | 1804 | |
| | 1805 | =head1 INCOMPATIBLE CHANGES TO OLD VERSION |
| | 1806 | |
| | 1807 | There are big incompatibility between new version (2.00) and old (1.xx). |
| | 1808 | If you use old C<JSON> 1.xx in your code, please check it. |
| | 1809 | |
| | 1810 | See to L<Transition ways from 1.xx to 2.xx.> |
| | 1811 | |
| | 1812 | =over |
| | 1813 | |
| | 1814 | =item jsonToObj and objToJson are obsoleted. |
| | 1815 | |
| | 1816 | Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted |
| | 1817 | (but not yet deleted from the source). |
| | 1818 | If you use these functions in your code, please replace them |
| | 1819 | with C<from_json> and C<to_json>. |
| | 1820 | |
| | 1821 | |
| | 1822 | =item Global variables are no longer available. |
| | 1823 | |
| | 1824 | C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc... |
| | 1825 | - are not avaliable any longer. |
| | 1826 | Instead, various features can be used through object methods. |
| | 1827 | |
| | 1828 | |
| | 1829 | =item Package JSON::Converter and JSON::Parser are deleted. |
| | 1830 | |
| | 1831 | Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them. |
| | 1832 | |
| | 1833 | =item Package JSON::NotString is deleted. |
| | 1834 | |
| | 1835 | There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null> |
| | 1836 | and numbers. It was deleted and replaced by C<JSON::Boolean>. |
| | 1837 | |
| | 1838 | C<JSON::Boolean> represents C<true> and C<false>. |
| | 1839 | |
| | 1840 | C<JSON::Boolean> does not represent C<null>. |
| | 1841 | |
| | 1842 | C<JSON::null> returns C<undef>. |
| | 1843 | |
| | 1844 | C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation |
| | 1845 | to L<JSON::Boolean>. |
| | 1846 | |
| | 1847 | =item function JSON::Number is obsoleted. |
| | 1848 | |
| | 1849 | C<JSON::Number> is now needless because JSON::XS and JSON::PP have |
| | 1850 | round-trip integrity. |
| | 1851 | |
| | 1852 | =item JSONRPC modules are deleted. |
| | 1853 | |
| | 1854 | Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP> |
| | 1855 | and C<Apache::JSONRPC > are deleted in this distribution. |
| | 1856 | Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1. |
| | 1857 | |
| | 1858 | =back |
| | 1859 | |
| | 1860 | =head2 Transition ways from 1.xx to 2.xx. |
| | 1861 | |
| | 1862 | You should set C<suport_by_pp> mode firstly, because |
| | 1863 | it is always successful for the below codes even with JSON::XS. |
| | 1864 | |
| | 1865 | use JSON -support_by_pp; |
| | 1866 | |
| | 1867 | =over |
| | 1868 | |
| | 1869 | =item Exported jsonToObj (simple) |
| | 1870 | |
| | 1871 | from_json($json_text); |
| | 1872 | |
| | 1873 | =item Exported objToJson (simple) |
| | 1874 | |
| | 1875 | to_json($perl_scalar); |
| | 1876 | |
| | 1877 | =item Exported jsonToObj (advanced) |
| | 1878 | |
| | 1879 | $flags = {allow_barekey => 1, allow_singlequote => 1}; |
| | 1880 | from_json($json_text, $flags); |
| | 1881 | |
| | 1882 | equivalent to: |
| | 1883 | |
| | 1884 | $JSON::BareKey = 1; |
| | 1885 | $JSON::QuotApos = 1; |
| | 1886 | jsonToObj($json_text); |
| | 1887 | |
| | 1888 | =item Exported objToJson (advanced) |
| | 1889 | |
| | 1890 | $flags = {allow_blessed => 1, allow_barekey => 1}; |
| | 1891 | to_json($perl_scalar, $flags); |
| | 1892 | |
| | 1893 | equivalent to: |
| | 1894 | |
| | 1895 | $JSON::BareKey = 1; |
| | 1896 | objToJson($perl_scalar); |
| | 1897 | |
| | 1898 | =item jsonToObj as object method |
| | 1899 | |
| | 1900 | $json->decode($json_text); |
| | 1901 | |
| | 1902 | =item objToJson as object method |
| | 1903 | |
| | 1904 | $json->encode($perl_scalar); |
| | 1905 | |
| | 1906 | =item new method with parameters |
| | 1907 | |
| | 1908 | The C<new> method in 2.x takes any parameters no longer. |
| | 1909 | You can set parameters instead; |
| | 1910 | |
| | 1911 | $json = JSON->new->pretty; |
| | 1912 | |
| | 1913 | =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter |
| | 1914 | |
| | 1915 | If C<indent> is enable, that menas C<$JSON::Pretty> flag set. And |
| | 1916 | C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>. |
| | 1917 | In conclusion: |
| | 1918 | |
| | 1919 | $json->indent->space_before->space_after; |
| | 1920 | |
| | 1921 | Equivalent to: |
| | 1922 | |
| | 1923 | $json->pretty; |
| | 1924 | |
| | 1925 | To change indent length, use C<indent_length>. |
| | 1926 | |
| | 1927 | (Only with JSON::PP, if C<-support_by_pp> is not used.) |
| | 1928 | |
| | 1929 | $json->pretty->indent_length(2)->encode($perl_scalar); |
| | 1930 | |
| | 1931 | =item $JSON::BareKey |
| | 1932 | |
| | 1933 | (Only with JSON::PP, if C<-support_by_pp> is not used.) |
| | 1934 | |
| | 1935 | $json->allow_barekey->decode($json_text) |
| | 1936 | |
| | 1937 | =item $JSON::ConvBlessed |
| | 1938 | |
| | 1939 | use C<-convert_blessed_universally>. See to L<convert_blessed>. |
| | 1940 | |
| | 1941 | =item $JSON::QuotApos |
| | 1942 | |
| | 1943 | (Only with JSON::PP, if C<-support_by_pp> is not used.) |
| | 1944 | |
| | 1945 | $json->allow_singlequote->decode($json_text) |
| | 1946 | |
| | 1947 | =item $JSON::SingleQuote |
| | 1948 | |
| | 1949 | Disable. C<JSON> does not make such a invalid JSON string any longer. |
| | 1950 | |
| | 1951 | =item $JSON::KeySort |
| | 1952 | |
| | 1953 | $json->canonical->encode($perl_scalar) |
| | 1954 | |
| | 1955 | This is the ascii sort. |
| | 1956 | |
| | 1957 | If you want to use with your own sort routine, check the C<sort_by> method. |
| | 1958 | |
| | 1959 | (Only with JSON::PP, even if C<-support_by_pp> is used currently.) |
| | 1960 | |
| | 1961 | $json->sort_by($sort_routine_ref)->encode($perl_scalar) |
| 309 | | (JSON) {"param" : {}} |
| 310 | | ( => Perl) {'param' => {}}; |
| 311 | | |
| 312 | | (JSON) {"param" : "string"} |
| 313 | | ( => Perl) {'param' => 'string'}; |
| 314 | | |
| 315 | | (JSON) {"param" : null} |
| 316 | | ( => Perl) {'param' => bless( {'value' => undef}, 'JSON::NotString' )}; |
| 317 | | |
| 318 | | (JSON) {"param" : true} |
| 319 | | ( => Perl) {'param' => bless( {'value' => 'true'}, 'JSON::NotString' )}; |
| 320 | | |
| 321 | | (JSON) {"param" : false} |
| 322 | | ( => Perl) {'param' => bless( {'value' => 'false'}, 'JSON::NotString' )}; |
| 323 | | |
| 324 | | (JSON) {"param" : -1.23} |
| 325 | | ( => Perl) {'param' => bless( {'value' => '-1.23'}, 'JSON::NotString' )}; |
| 326 | | |
| 327 | | (JSON) {"param" : 0xff} |
| 328 | | ( => Perl) {'param' => 255}; |
| 329 | | |
| 330 | | (JSON) {"param" : 010} |
| 331 | | ( => Perl) {'param' => 8}; |
| 332 | | |
| 333 | | These JSON::NotString objects are overloaded so you don't care about. |
| 334 | | |
| 335 | | Perl's C<undef> is converted to 'null'. |
| 336 | | |
| 337 | | |
| 338 | | =head1 PRETY PRINTING |
| 339 | | |
| 340 | | If you'd like your JSON output to be pretty-printed, pass the C<pretty> |
| 341 | | parameter to objToJson(). You can affect the indentation (which defaults to 2) |
| 342 | | by passing the C<indent> parameter to objToJson(). |
| 343 | | |
| 344 | | my $str = $json->objToJson($obj, {pretty => 1, indent => 4}); |
| 345 | | |
| 346 | | In addition, you can set some number to C<delimiter> option. |
| 347 | | The available numbers are only 0, 1 and 2. |
| 348 | | In pretty-printing mode, when C<delimiter> is 1, one space is added |
| 349 | | after ':' in object keys. If C<delimiter> is 2, it is ' : ' and |
| 350 | | 0 is ':' (default is 2). If you give 3 or more to it, the value |
| 351 | | is taken as 2. |
| 352 | | |
| 353 | | |
| 354 | | =head1 AUTOCONVERT |
| 355 | | |
| 356 | | By default, $JSON::AUTOCONVERT is true. |
| 357 | | |
| 358 | | (Perl) {num => 10.02} |
| 359 | | ( => JSON) {"num" : 10.02} |
| 360 | | |
| 361 | | it is not C<{"num" : "10.02"}>. |
| 362 | | |
| 363 | | But set false value with $JSON::AUTOCONVERT: |
| 364 | | |
| 365 | | (Perl) {num => 10.02} |
| 366 | | ( => JSON) {"num" : "10.02"} |
| 367 | | |
| 368 | | it is not C<{"num" : 10.02}>. |
| 369 | | |
| 370 | | You can explicitly sepcify: |
| 371 | | |
| 372 | | $obj = { |
| 373 | | id => JSON::Number(10.02), |
| 374 | | bool1 => JSON::True, |
| 375 | | bool2 => JSON::False, |
| 376 | | noval => JSON::Null, |
| 377 | | }; |
| 378 | | |
| 379 | | $json->objToJson($obj); |
| 380 | | # {"noval" : null, "bool2" : false, "bool1" : true, "id" : 10.02} |
| 381 | | |
| 382 | | C<JSON::Number()> returns C<undef> when an argument invalid format. |
| 383 | | |
| 384 | | |
| 385 | | =head1 EXPORT |
| 386 | | |
| 387 | | C<objToJson>, C<jsonToObj>. |
| | 1963 | $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar) |
| | 1964 | |
| | 1965 | Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>. |
| | 1966 | |
| | 1967 | =item $JSON::SkipInvalid |
| | 1968 | |
| | 1969 | $json->allow_unknown |
| | 1970 | |
| | 1971 | =item $JSON::AUTOCONVERT |
| | 1972 | |
| | 1973 | Needless. C<JSON> backend modules have the round-trip integrity. |
| | 1974 | |
| | 1975 | =item $JSON::UTF8 |
| | 1976 | |
| | 1977 | Needless because C<JSON> (JSON::XS/JSON::PP) sets |
| | 1978 | the UTF8 flag on properly. |
| | 1979 | |
| | 1980 | # With UTF8-flagged strings |
| | 1981 | |
| | 1982 | $json->allow_nonref; |
| | 1983 | $str = chr(1000); # UTF8-flagged |
| | 1984 | |
| | 1985 | $json_text = $json->utf8(0)->encode($str); |
| | 1986 | utf8::is_utf8($json_text); |
| | 1987 | # true |
| | 1988 | $json_text = $json->utf8(1)->encode($str); |
| | 1989 | utf8::is_utf8($json_text); |
| | 1990 | # false |
| | 1991 | |
| | 1992 | $str = '"' . chr(1000) . '"'; # UTF8-flagged |
| | 1993 | |
| | 1994 | $perl_scalar = $json->utf8(0)->decode($str); |
| | 1995 | utf8::is_utf8($perl_scalar); |
| | 1996 | # true |
| | 1997 | $perl_scalar = $json->utf8(1)->decode($str); |
| | 1998 | # died because of 'Wide character in subroutine' |
| | 1999 | |
| | 2000 | See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>. |
| | 2001 | |
| | 2002 | =item $JSON::UnMapping |
| | 2003 | |
| | 2004 | Disable. See to L<MAPPING>. |
| | 2005 | |
| | 2006 | =item $JSON::SelfConvert |
| | 2007 | |
| | 2008 | This option was deleted. |
| | 2009 | Instead of it, if a givien blessed object has the C<TO_JSON> method, |
| | 2010 | C<TO_JSON> will be executed with C<convert_blessed>. |
| | 2011 | |
| | 2012 | $json->convert_blessed->encode($bleesed_hashref_or_arrayref) |
| | 2013 | # if need, call allow_blessed |
| | 2014 | |
| | 2015 | Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>. |
| | 2016 | |
| | 2017 | =back |