home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / perl5 / JSON.pm < prev    next >
Encoding:
Perl POD Document  |  2010-04-05  |  64.5 KB  |  2,221 lines

  1. package JSON;
  2.  
  3.  
  4. use strict;
  5. use Carp ();
  6. use base qw(Exporter);
  7. @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
  8.  
  9. BEGIN {
  10.     $JSON::VERSION = '2.21';
  11.     $JSON::DEBUG   = 0 unless (defined $JSON::DEBUG);
  12. }
  13.  
  14. my $Module_XS  = 'JSON::XS';
  15. my $Module_PP  = 'JSON::PP';
  16. my $XS_Version = '2.27';
  17.  
  18.  
  19. # XS and PP common methods
  20.  
  21. my @PublicMethods = qw/
  22.     ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref 
  23.     allow_blessed convert_blessed filter_json_object filter_json_single_key_object 
  24.     shrink max_depth max_size encode decode decode_prefix allow_unknown
  25. /;
  26.  
  27. my @Properties = qw/
  28.     ascii latin1 utf8 indent space_before space_after relaxed canonical allow_nonref
  29.     allow_blessed convert_blessed shrink max_depth max_size allow_unknown
  30. /;
  31.  
  32. my @XSOnlyMethods = qw//; # Currently nothing
  33.  
  34. my @PPOnlyMethods = qw/
  35.     indent_length sort_by
  36.     allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed
  37. /; # JSON::PP specific
  38.  
  39.  
  40. # used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently)
  41. my $_INSTALL_DONT_DIE  = 1; # When _load_xs fails to load XS, don't die.
  42. my $_INSTALL_ONLY      = 2; # Don't call _set_methods()
  43. my $_ALLOW_UNSUPPORTED = 0;
  44. my $_UNIV_CONV_BLESSED = 0;
  45.  
  46.  
  47. # Check the environment variable to decide worker module. 
  48.  
  49. unless ($JSON::Backend) {
  50.     $JSON::DEBUG and  Carp::carp("Check used worker module...");
  51.  
  52.     my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1;
  53.  
  54.     if ($backend eq '1' or $backend =~ /JSON::XS\s*,\s*JSON::PP/) {
  55.         _load_xs($_INSTALL_DONT_DIE) or _load_pp();
  56.     }
  57.     elsif ($backend eq '0' or $backend eq 'JSON::PP') {
  58.         _load_pp();
  59.     }
  60.     elsif ($backend eq '2' or $backend eq 'JSON::XS') {
  61.         _load_xs();
  62.     }
  63.     else {
  64.         Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid.";
  65.     }
  66. }
  67.  
  68.  
  69. sub import {
  70.     my $pkg = shift;
  71.     my @what_to_export;
  72.     my $no_export;
  73.  
  74.     for my $tag (@_) {
  75.         if ($tag eq '-support_by_pp') {
  76.             if (!$_ALLOW_UNSUPPORTED++) {
  77.                 JSON::Backend::XS
  78.                     ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend eq $Module_XS);
  79.             }
  80.             next;
  81.         }
  82.         elsif ($tag eq '-no_export') {
  83.             $no_export++, next;
  84.         }
  85.         elsif ( $tag eq '-convert_blessed_universally' ) {
  86.             eval q|
  87.                 require B;
  88.                 *UNIVERSAL::TO_JSON = sub {
  89.                     my $b_obj = B::svref_2object( $_[0] );
  90.                     return    $b_obj->isa('B::HV') ? { %{ $_[0] } }
  91.                             : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
  92.                             : undef
  93.                             ;
  94.                 }
  95.             | if ( !$_UNIV_CONV_BLESSED++ );
  96.             next;
  97.         }
  98.         push @what_to_export, $tag;
  99.     }
  100.  
  101.     return if ($no_export);
  102.  
  103.     __PACKAGE__->export_to_level(1, $pkg, @what_to_export);
  104. }
  105.  
  106.  
  107. # OBSOLETED
  108.  
  109. sub jsonToObj {
  110.     my $alternative = 'from_json';
  111.     if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
  112.         shift @_; $alternative = 'decode';
  113.     }
  114.     Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead.";
  115.     return JSON::from_json(@_);
  116. };
  117.  
  118. sub objToJson {
  119.     my $alternative = 'to_json';
  120.     if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
  121.         shift @_; $alternative = 'encode';
  122.     }
  123.     Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead.";
  124.     JSON::to_json(@_);
  125. };
  126.  
  127.  
  128. # INTERFACES
  129.  
  130. sub to_json ($@) {
  131.     my $json = new JSON;
  132.  
  133.     if (@_ == 2 and ref $_[1] eq 'HASH') {
  134.         my $opt  = $_[1];
  135.         for my $method (keys %$opt) {
  136.             $json->$method( $opt->{$method} );
  137.         }
  138.     }
  139.  
  140.     $json->encode($_[0]);
  141. }
  142.  
  143.  
  144. sub from_json ($@) {
  145.     my $json = new JSON;
  146.  
  147.     if (@_ == 2 and ref $_[1] eq 'HASH') {
  148.         my $opt  = $_[1];
  149.         for my $method (keys %$opt) {
  150.             $json->$method( $opt->{$method} );
  151.         }
  152.     }
  153.  
  154.     return $json->decode( $_[0] );
  155. }
  156.  
  157.  
  158. sub true  { $JSON::true  }
  159.  
  160. sub false { $JSON::false }
  161.  
  162. sub null  { undef; }
  163.  
  164.  
  165. sub require_xs_version { $XS_Version; }
  166.  
  167. sub backend {
  168.     my $proto = shift;
  169.     $JSON::Backend;
  170. }
  171.  
  172. #*module = *backend;
  173.  
  174.  
  175. sub is_xs {
  176.     return $_[0]->module eq $Module_XS;
  177. }
  178.  
  179.  
  180. sub is_pp {
  181.     return $_[0]->module eq $Module_PP;
  182. }
  183.  
  184.  
  185. sub pureperl_only_methods { @PPOnlyMethods; }
  186.  
  187.  
  188. sub property {
  189.     my ($self, $name, $value) = @_;
  190.  
  191.     if (@_ == 1) {
  192.         my %props;
  193.         for $name (@Properties) {
  194.             my $method = 'get_' . $name;
  195.             if ($name eq 'max_size') {
  196.                 my $value = $self->$method();
  197.                 $props{$name} = $value == 1 ? 0 : $value;
  198.                 next;
  199.             }
  200.             $props{$name} = $self->$method();
  201.         }
  202.         return \%props;
  203.     }
  204.     elsif (@_ > 3) {
  205.         Carp::croak('property() can take only the option within 2 arguments.');
  206.     }
  207.     elsif (@_ == 2) {
  208.         if ( my $method = $self->can('get_' . $name) ) {
  209.             if ($name eq 'max_size') {
  210.                 my $value = $self->$method();
  211.                 return $value == 1 ? 0 : $value;
  212.             }
  213.             $self->$method();
  214.         }
  215.     }
  216.     else {
  217.         $self->$name($value);
  218.     }
  219.  
  220. }
  221.  
  222.  
  223.  
  224. # INTERNAL
  225.  
  226. sub _load_xs {
  227.     my $opt = shift;
  228.  
  229.     $JSON::DEBUG and Carp::carp "Load $Module_XS.";
  230.  
  231.     # if called after install module, overload is disable.... why?
  232.     JSON::Boolean::_overrride_overload($Module_XS);
  233.     JSON::Boolean::_overrride_overload($Module_PP);
  234.  
  235.     eval qq|
  236.         use $Module_XS $XS_Version ();
  237.     |;
  238.  
  239.     if ($@) {
  240.         if (defined $opt and $opt & $_INSTALL_DONT_DIE) {
  241.             $JSON::DEBUG and Carp::carp "Can't load $Module_XS...($@)";
  242.             return 0;
  243.         }
  244.         Carp::croak $@;
  245.     }
  246.  
  247.     unless (defined $opt and $opt & $_INSTALL_ONLY) {
  248.         _set_module( $JSON::Backend = $Module_XS );
  249.         my $data = join("", <DATA>); # this code is from Jcode 2.xx.
  250.         close(DATA);
  251.         eval $data;
  252.         JSON::Backend::XS->init;
  253.     }
  254.  
  255.     return 1;
  256. };
  257.  
  258.  
  259. sub _load_pp {
  260.     my $opt = shift;
  261.  
  262.     $JSON::DEBUG and Carp::carp "Load $Module_PP.";
  263.  
  264.     # if called after install module, overload is disable.... why?
  265.     JSON::Boolean::_overrride_overload($Module_XS);
  266.     JSON::Boolean::_overrride_overload($Module_PP);
  267.  
  268.     eval qq| require $Module_PP |;
  269.     if ($@) {
  270.         Carp::croak $@;
  271.     }
  272.  
  273.     unless (defined $opt and $opt & $_INSTALL_ONLY) {
  274.         _set_module( $JSON::Backend = $Module_PP );
  275.         JSON::Backend::PP->init;
  276.     }
  277. };
  278.  
  279.  
  280. sub _set_module {
  281.     my $module = shift;
  282.  
  283.     local $^W;
  284.     no strict qw(refs);
  285.  
  286.     $JSON::true  = ${"$module\::true"};
  287.     $JSON::false = ${"$module\::false"};
  288.  
  289.     push @JSON::ISA, $module;
  290.     push @{"$module\::Boolean::ISA"}, qw(JSON::Boolean);
  291.  
  292.     *{"JSON::is_bool"} = \&{"$module\::is_bool"};
  293.  
  294.     for my $method ($module eq $Module_XS ? @PPOnlyMethods : @XSOnlyMethods) {
  295.         *{"JSON::$method"} = sub {
  296.             Carp::carp("$method is not supported in $module.");
  297.             $_[0];
  298.         };
  299.     }
  300.  
  301.     return 1;
  302. }
  303.  
  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.  
  418.     for my $method (@methods) {
  419.         my $flag = uc($method);
  420.         my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0);
  421.            $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0);
  422.  
  423.         next unless($type);
  424.  
  425.         $pkg->_make_unsupported_method($method => $type);
  426.     }
  427.  
  428.     push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
  429.     push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
  430.  
  431.     $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
  432.  
  433.     return 1;
  434. }
  435.  
  436.  
  437.  
  438.  
  439. #
  440. # Helper classes for XS
  441. #
  442.  
  443. package JSON::Backend::XS::Supportable;
  444.  
  445. {
  446.     my $JSON_XS_encode_orignal = \&JSON::XS::encode;
  447.     my $JSON_XS_decode_orignal = \&JSON::XS::decode;
  448.     my $JSON_XS_incr_parse_orignal = \&JSON::XS::incr_parse;
  449.  
  450.     local $^W;
  451.     *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode;
  452.     *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
  453.     *JSON::XS::incr_parse = \&JSON::Backend::XS::Supportable::_incr_parse;
  454.  
  455.     *{JSON::XS::_original_decode} = $JSON_XS_decode_orignal;
  456.     *{JSON::XS::_original_encode} = $JSON_XS_encode_orignal;
  457.     *{JSON::XS::_original_incr_parse} = $JSON_XS_incr_parse_orignal;
  458. }
  459.  
  460. $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
  461.  
  462. sub _make_unsupported_method {
  463.     my ($pkg, $method, $type) = @_;
  464.  
  465.     local $^W;
  466.     no strict qw(refs);
  467.  
  468.     *{"$pkg\::$method"} = sub {
  469.         local $^W;
  470.         if (defined $_[1] ? $_[1] : 1) {
  471.             ${$_[0]} |= $type;
  472.         }
  473.         else {
  474.             ${$_[0]} &= ~$type;
  475.         }
  476.         $_[0];
  477.     };
  478.  
  479.     *{"$pkg\::get_$method"} = sub {
  480.         ${$_[0]} & $type ? 1 : '';
  481.     };
  482.  
  483. }
  484.  
  485.  
  486. sub _set_for_pp {
  487.     require JSON::PP;
  488.     my $type  = shift;
  489.     my $pp    = new JSON::PP;
  490.     my $prop = $_[0]->property;
  491.  
  492.     for my $name (keys %$prop) {
  493.         $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
  494.     }
  495.  
  496.     my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
  497.                                         : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
  498.     my $flags       = ${$_[0]} || 0;
  499.  
  500.     for my $name (keys %$unsupported) {
  501.         next if ($name eq 'EXPANDED'); # for developer's
  502.         my $enable = ($flags & $unsupported->{$name}) ? 1 : 0;
  503.         my $method = lc $name;
  504.         $pp->$method($enable);
  505.     }
  506.  
  507.     $pp->indent_length( $_[0]->get_indent_length );
  508.  
  509.     return $pp;
  510. }
  511.  
  512. sub _encode { # using with PP encod
  513.     if (${$_[0]}) {
  514.         _set_for_pp('encode' => @_)->encode($_[1]);
  515.     }
  516.     else {
  517.         $_[0]->_original_encode( $_[1] );
  518.     }
  519. }
  520.  
  521.  
  522. sub _decode { # if unsupported-flag is set, use PP
  523.     if (${$_[0]}) {
  524.         _set_for_pp('decode' => @_)->decode($_[1]);
  525.     }
  526.     else {
  527.         $_[0]->_original_decode( $_[1] );
  528.     }
  529. }
  530.  
  531.  
  532. sub decode_prefix { # if unsupported-flag is set, use PP
  533.     _set_for_pp('decode' => @_)->decode_prefix($_[1]);
  534. }
  535.  
  536.  
  537. sub _incr_parse {
  538.     if (${$_[0]}) {
  539.         _set_for_pp('decode' => @_)->incr_parse($_[1]);
  540.     }
  541.     else {
  542.         $_[0]->_original_incr_parse( $_[1] );
  543.     }
  544. }
  545.  
  546.  
  547. sub get_indent_length {
  548.     ${$_[0]} << 4 >> 16;
  549. }
  550.  
  551.  
  552. sub indent_length {
  553.     my $length = $_[1];
  554.  
  555.     if (!defined $length or $length > 15 or $length < 0) {
  556.         Carp::carp "The acceptable range of indent_length() is 0 to 15.";
  557.     }
  558.     else {
  559.         local $^W;
  560.         $length <<= 12;
  561.         ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
  562.         ${$_[0]} |= $length;
  563.         *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
  564.     }
  565.  
  566.     $_[0];
  567. }
  568.  
  569.  
  570. 1;
  571. __END__
  572.  
  573. =head1 NAME
  574.  
  575. JSON - JSON (JavaScript Object Notation) encoder/decoder
  576.  
  577. =head1 SYNOPSIS
  578.  
  579.  use JSON; # imports encode_json, decode_json, to_json and from_json.
  580.  
  581.  # simple and fast interfaces (expect/generate UTF-8)
  582.  
  583.  $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
  584.  $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
  585.  
  586.  # OO-interface
  587.  
  588.  $json = JSON->new->allow_nonref;
  589.  
  590.  $json_text   = $json->encode( $perl_scalar );
  591.  $perl_scalar = $json->decode( $json_text );
  592.  
  593.  $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
  594.  
  595.  # If you want to use PP only support features, call with '-support_by_pp'
  596.  # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
  597.  
  598.  use JSON -support_by_pp;
  599.  
  600.  # option-acceptable interfaces (expect/generate UNICODE by default)
  601.  
  602.  $json_text   = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
  603.  $perl_scalar = from_json( $json_text, { utf8  => 1 } );
  604.  
  605.  # Between (en|de)code_json and (to|from)_json, if you want to write
  606.  # a code which communicates to an outer world (encoded in UTF-8),
  607.  # recommend to use (en|de)code_json.
  608.  
  609. =head1 VERSION
  610.  
  611.     2.21
  612.  
  613. This version is compatible with JSON::XS B<2.27> and later.
  614.  
  615.  
  616. =head1 DESCRIPTION
  617.  
  618.  ************************** CAUTION ********************************
  619.  * This is 'JSON module version 2' and there are many differences  *
  620.  * to version 1.xx                                                 *
  621.  * Please check your applications useing old version.              *
  622.  *   See to 'INCOMPATIBLE CHANGES TO OLD VERSION'                  *
  623.  *******************************************************************
  624.  
  625. JSON (JavaScript Object Notation) is a simple data format.
  626. See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
  627.  
  628. This module converts Perl data structures to JSON and vice versa using either
  629. L<JSON::XS> or L<JSON::PP>.
  630.  
  631. JSON::XS is the fastest and most proper JSON module on CPAN which must be
  632. compiled and installed in your environment.
  633. JSON::PP is a pure-Perl module which is bundled in this distribution and
  634. has a strong compatibility to JSON::XS.
  635.  
  636. This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
  637. So its features completely depend on JSON::XS or JSON::PP.
  638.  
  639. See to L<BACKEND MODULE DECISION>.
  640.  
  641. To distinguish the module name 'JSON' and the format type JSON,
  642. the former is quoted by CE<lt>E<gt> (its results vary with your using media),
  643. and the latter is left just as it is.
  644.  
  645. Module name : C<JSON>
  646.  
  647. Format type : JSON
  648.  
  649. =head2 FEATURES
  650.  
  651. =over
  652.  
  653. =item * correct unicode handling
  654.  
  655. This module (i.e. backend modules) knows how to handle Unicode, documents
  656. how and when it does so, and even documents what "correct" means.
  657.  
  658. Even though there are limitations, this feature is available since Perl version 5.6.
  659.  
  660. JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
  661. C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005.
  662.  
  663. With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
  664. JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
  665. See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
  666.  
  667. See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
  668. and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
  669.  
  670.  
  671. =item * round-trip integrity
  672.  
  673. When you serialise a perl data structure using only data types supported
  674. by JSON and Perl, the deserialised data structure is identical on the Perl
  675. level. (e.g. the string "2.0" doesn't suddenly become "2" just because
  676. it looks like a number). There I<are> minor exceptions to this, read the
  677. L</MAPPING> section below to learn about those.
  678.  
  679.  
  680. =item * strict checking of JSON correctness
  681.  
  682. There is no guessing, no generating of illegal JSON texts by default,
  683. and only JSON is accepted as input by default (the latter is a security
  684. feature).
  685.  
  686. See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
  687.  
  688. =item * fast
  689.  
  690. This module returns a JSON::XS object itself if available.
  691. Compared to other JSON modules and other serialisers such as Storable,
  692. JSON::XS usually compares favourably in terms of speed, too.
  693.  
  694. If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
  695. it is very slow as pure-Perl.
  696.  
  697. =item * simple to use
  698.  
  699. This module has both a simple functional interface as well as an
  700. object oriented interface interface.
  701.  
  702. =item * reasonably versatile output formats
  703.  
  704. You can choose between the most compact guaranteed-single-line format possible
  705. (nice for simple line-based protocols), a pure-ASCII format (for when your transport
  706. is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
  707. format (for when you want to read that stuff). Or you can combine those features
  708. in whatever way you like.
  709.  
  710. =back
  711.  
  712. =head1 FUNCTIONAL INTERFACE
  713.  
  714. Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
  715. C<to_json> and C<from_json> are additional functions.
  716.  
  717. =head2 encode_json
  718.  
  719.     $json_text = encode_json $perl_scalar
  720.  
  721. Converts the given Perl data structure to a UTF-8 encoded, binary string.
  722.  
  723. This function call is functionally identical to:
  724.  
  725.     $json_text = JSON->new->utf8->encode($perl_scalar)
  726.  
  727. =head2 decode_json
  728.  
  729.     $perl_scalar = decode_json $json_text
  730.  
  731. The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
  732. to parse that as an UTF-8 encoded JSON text, returning the resulting
  733. reference.
  734.  
  735. This function call is functionally identical to:
  736.  
  737.     $perl_scalar = JSON->new->utf8->decode($json_text)
  738.  
  739.  
  740. =head2 to_json
  741.  
  742.    $json_text = to_json($perl_scalar)
  743.  
  744. Converts the given Perl data structure to a json string.
  745.  
  746. This function call is functionally identical to:
  747.  
  748.    $json_text = JSON->new->encode($perl_scalar)
  749.  
  750. Takes a hash reference as the second.
  751.  
  752.    $json_text = to_json($perl_scalar, $flag_hashref)
  753.  
  754. So,
  755.  
  756.    $json_text = encode_json($perl_scalar, {utf8 => 1, pretty => 1})
  757.  
  758. equivalent to:
  759.  
  760.    $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
  761.  
  762. If you want to write a modern perl code which communicates to outer world,
  763. you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
  764.  
  765. =head2 from_json
  766.  
  767.    $perl_scalar = from_json($json_text)
  768.  
  769. The opposite of C<to_json>: expects a json string and tries
  770. to parse it, returning the resulting reference.
  771.  
  772. This function call is functionally identical to:
  773.  
  774.     $perl_scalar = JSON->decode($json_text)
  775.  
  776. Takes a hash reference as the second.
  777.  
  778.     $perl_scalar = from_json($json_text, $flag_hashref)
  779.  
  780. So,
  781.  
  782.     $perl_scalar = from_json($json_text, {utf8 => 1})
  783.  
  784. equivalent to:
  785.  
  786.     $perl_scalar = JSON->new->utf8(1)->decode($json_text)
  787.  
  788. If you want to write a modern perl code which communicates to outer world,
  789. you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
  790.  
  791. =head2 JSON::is_bool
  792.  
  793.     $is_boolean = JSON::is_bool($scalar)
  794.  
  795. Returns true if the passed scalar represents either JSON::true or
  796. JSON::false, two constants that act like C<1> and C<0> respectively
  797. and are also used to represent JSON C<true> and C<false> in Perl strings.
  798.  
  799. =head2 JSON::true
  800.  
  801. Returns JSON true value which is blessed object.
  802. It C<isa> JSON::Boolean object.
  803.  
  804. =head2 JSON::false
  805.  
  806. Returns JSON false value which is blessed object.
  807. It C<isa> JSON::Boolean object.
  808.  
  809. =head2 JSON::null
  810.  
  811. Returns C<undef>.
  812.  
  813. See L<MAPPING>, below, for more information on how JSON values are mapped to
  814. Perl.
  815.  
  816. =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
  817.  
  818. This section supposes that your perl vresion is 5.8 or later.
  819.  
  820. If you know a JSON text from an outer world - a network, a file content, and so on,
  821. is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
  822. with C<utf8> enable. And the decoded result will contain UNICODE characters.
  823.  
  824.   # from network
  825.   my $json        = JSON->new->utf8;
  826.   my $json_text   = CGI->new->param( 'json_data' );
  827.   my $perl_scalar = $json->decode( $json_text );
  828.   
  829.   # from file content
  830.   local $/;
  831.   open( my $fh, '<', 'json.data' );
  832.   $json_text   = <$fh>;
  833.   $perl_scalar = decode_json( $json_text );
  834.  
  835. If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
  836.  
  837.   use Encode;
  838.   local $/;
  839.   open( my $fh, '<', 'json.data' );
  840.   my $encoding = 'cp932';
  841.   my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
  842.   
  843.   # or you can write the below code.
  844.   #
  845.   # open( my $fh, "<:encoding($encoding)", 'json.data' );
  846.   # $unicode_json_text = <$fh>;
  847.  
  848. In this case, C<$unicode_json_text> is of course UNICODE string.
  849. So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
  850. Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
  851.  
  852.   $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
  853.   # or
  854.   $perl_scalar = from_json( $unicode_json_text );
  855.  
  856. Or C<encode 'utf8'> and C<decode_json>:
  857.  
  858.   $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
  859.   # this way is not efficient.
  860.  
  861. And now, you want to convert your C<$perl_scalar> into JSON data and
  862. send it to an outer world - a network or a file content, and so on.
  863.  
  864. Your data usually contains UNICODE strings and you want the converted data to be encoded
  865. in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
  866.  
  867.   print encode_json( $perl_scalar ); # to a network? file? or display?
  868.   # or
  869.   print $json->utf8->encode( $perl_scalar );
  870.  
  871. If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
  872. for some reason, then its characters are regarded as B<latin1> for perl
  873. (because it does not concern with your $encoding).
  874. You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
  875. Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
  876. Note that the resulted text is a UNICODE string but no problem to print it.
  877.  
  878.   # $perl_scalar contains $encoding encoded string values
  879.   $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
  880.   # or 
  881.   $unicode_json_text = to_json( $perl_scalar );
  882.   # $unicode_json_text consists of characters less than 0x100
  883.   print $unicode_json_text;
  884.  
  885. Or C<decode $encoding> all string values and C<encode_json>:
  886.  
  887.   $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
  888.   # ... do it to each string values, then encode_json
  889.   $json_text = encode_json( $perl_scalar );
  890.  
  891. This method is a proper way but probably not efficient.
  892.  
  893. See to L<Encode>, L<perluniintro>.
  894.  
  895.  
  896. =head1 COMMON OBJECT-ORIENTED INTERFACE
  897.  
  898. =head2 new
  899.  
  900.     $json = new JSON
  901.  
  902. Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
  903. that can be used to de/encode JSON strings.
  904.  
  905. All boolean flags described below are by default I<disabled>.
  906.  
  907. The mutators for flags all return the JSON object again and thus calls can
  908. be chained:
  909.  
  910.    my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
  911.    => {"a": [1, 2]}
  912.  
  913. =head2 ascii
  914.  
  915.     $json = $json->ascii([$enable])
  916.     
  917.     $enabled = $json->get_ascii
  918.  
  919. If $enable is true (or missing), then the encode method will not generate characters outside
  920. the code range 0..127. Any Unicode characters outside that range will be escaped using either
  921. a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
  922.  
  923. If $enable is false, then the encode method will not escape Unicode characters unless
  924. required by the JSON syntax or other flags. This results in a faster and more compact format.
  925.  
  926. This feature depends on the used Perl version and environment.
  927.  
  928. See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
  929.  
  930.   JSON->new->ascii(1)->encode([chr 0x10401])
  931.   => ["\ud801\udc01"]
  932.  
  933. =head2 latin1
  934.  
  935.     $json = $json->latin1([$enable])
  936.     
  937.     $enabled = $json->get_latin1
  938.  
  939. If $enable is true (or missing), then the encode method will encode the resulting JSON
  940. text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
  941.  
  942. If $enable is false, then the encode method will not escape Unicode characters
  943. unless required by the JSON syntax or other flags.
  944.  
  945.   JSON->new->latin1->encode (["\x{89}\x{abc}"]
  946.   => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
  947.  
  948. =head2 utf8
  949.  
  950.     $json = $json->utf8([$enable])
  951.     
  952.     $enabled = $json->get_utf8
  953.  
  954. If $enable is true (or missing), then the encode method will encode the JSON result
  955. into UTF-8, as required by many protocols, while the decode method expects to be handled
  956. an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
  957. characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
  958.  
  959. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
  960. encoding families, as described in RFC4627.
  961.  
  962. If $enable is false, then the encode method will return the JSON string as a (non-encoded)
  963. Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
  964. (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
  965.  
  966.  
  967. Example, output UTF-16BE-encoded JSON:
  968.  
  969.   use Encode;
  970.   $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
  971.  
  972. Example, decode UTF-32LE-encoded JSON:
  973.  
  974.   use Encode;
  975.   $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
  976.  
  977. See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
  978.  
  979.  
  980. =head2 pretty
  981.  
  982.     $json = $json->pretty([$enable])
  983.  
  984. This enables (or disables) all of the C<indent>, C<space_before> and
  985. C<space_after> (and in the future possibly more) flags in one call to
  986. generate the most readable (or most compact) form possible.
  987.  
  988. Equivalent to:
  989.  
  990.    $json->indent->space_before->space_after
  991.  
  992. The indent space length is three and JSON::XS cannot change the indent
  993. space length.
  994.  
  995. =head2 indent
  996.  
  997.     $json = $json->indent([$enable])
  998.     
  999.     $enabled = $json->get_indent
  1000.  
  1001. If C<$enable> is true (or missing), then the C<encode> method will use a multiline
  1002. format as output, putting every array member or object/hash key-value pair
  1003. into its own line, identing them properly.
  1004.  
  1005. If C<$enable> is false, no newlines or indenting will be produced, and the
  1006. resulting JSON text is guarenteed not to contain any C<newlines>.
  1007.  
  1008. This setting has no effect when decoding JSON texts.
  1009.  
  1010. The indent space length is three.
  1011. With JSON::PP, you can also access C<indent_length> to change indent space length.
  1012.  
  1013.  
  1014. =head2 space_before
  1015.  
  1016.     $json = $json->space_before([$enable])
  1017.     
  1018.     $enabled = $json->get_space_before
  1019.  
  1020. If C<$enable> is true (or missing), then the C<encode> method will add an extra
  1021. optional space before the C<:> separating keys from values in JSON objects.
  1022.  
  1023. If C<$enable> is false, then the C<encode> method will not add any extra
  1024. space at those places.
  1025.  
  1026. This setting has no effect when decoding JSON texts.
  1027.  
  1028. Example, space_before enabled, space_after and indent disabled:
  1029.  
  1030.    {"key" :"value"}
  1031.  
  1032.  
  1033. =head2 space_after
  1034.  
  1035.     $json = $json->space_after([$enable])
  1036.     
  1037.     $enabled = $json->get_space_after
  1038.  
  1039. If C<$enable> is true (or missing), then the C<encode> method will add an extra
  1040. optional space after the C<:> separating keys from values in JSON objects
  1041. and extra whitespace after the C<,> separating key-value pairs and array
  1042. members.
  1043.  
  1044. If C<$enable> is false, then the C<encode> method will not add any extra
  1045. space at those places.
  1046.  
  1047. This setting has no effect when decoding JSON texts.
  1048.  
  1049. Example, space_before and indent disabled, space_after enabled:
  1050.  
  1051.    {"key": "value"}
  1052.  
  1053.  
  1054. =head2 relaxed
  1055.  
  1056.     $json = $json->relaxed([$enable])
  1057.     
  1058.     $enabled = $json->get_relaxed
  1059.  
  1060. If C<$enable> is true (or missing), then C<decode> will accept some
  1061. extensions to normal JSON syntax (see below). C<encode> will not be
  1062. affected in anyway. I<Be aware that this option makes you accept invalid
  1063. JSON texts as if they were valid!>. I suggest only to use this option to
  1064. parse application-specific files written by humans (configuration files,
  1065. resource files etc.)
  1066.  
  1067. If C<$enable> is false (the default), then C<decode> will only accept
  1068. valid JSON texts.
  1069.  
  1070. Currently accepted extensions are:
  1071.  
  1072. =over 4
  1073.  
  1074. =item * list items can have an end-comma
  1075.  
  1076. JSON I<separates> array elements and key-value pairs with commas. This
  1077. can be annoying if you write JSON texts manually and want to be able to
  1078. quickly append elements, so this extension accepts comma at the end of
  1079. such items not just between them:
  1080.  
  1081.    [
  1082.       1,
  1083.       2, <- this comma not normally allowed
  1084.    ]
  1085.    {
  1086.       "k1": "v1",
  1087.       "k2": "v2", <- this comma not normally allowed
  1088.    }
  1089.  
  1090. =item * shell-style '#'-comments
  1091.  
  1092. Whenever JSON allows whitespace, shell-style comments are additionally
  1093. allowed. They are terminated by the first carriage-return or line-feed
  1094. character, after which more white-space and comments are allowed.
  1095.  
  1096.   [
  1097.      1, # this comment not allowed in JSON
  1098.         # neither this one...
  1099.   ]
  1100.  
  1101. =back
  1102.  
  1103.  
  1104. =head2 canonical
  1105.  
  1106.     $json = $json->canonical([$enable])
  1107.     
  1108.     $enabled = $json->get_canonical
  1109.  
  1110. If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
  1111. by sorting their keys. This is adding a comparatively high overhead.
  1112.  
  1113. If C<$enable> is false, then the C<encode> method will output key-value
  1114. pairs in the order Perl stores them (which will likely change between runs
  1115. of the same script).
  1116.  
  1117. This option is useful if you want the same data structure to be encoded as
  1118. the same JSON text (given the same overall settings). If it is disabled,
  1119. the same hash might be encoded differently even if contains the same data,
  1120. as key-value pairs have no inherent ordering in Perl.
  1121.  
  1122. This setting has no effect when decoding JSON texts.
  1123.  
  1124. =head2 allow_nonref
  1125.  
  1126.     $json = $json->allow_nonref([$enable])
  1127.     
  1128.     $enabled = $json->get_allow_nonref
  1129.  
  1130. If C<$enable> is true (or missing), then the C<encode> method can convert a
  1131. non-reference into its corresponding string, number or null JSON value,
  1132. which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
  1133. values instead of croaking.
  1134.  
  1135. If C<$enable> is false, then the C<encode> method will croak if it isn't
  1136. passed an arrayref or hashref, as JSON texts must either be an object
  1137. or array. Likewise, C<decode> will croak if given something that is not a
  1138. JSON object or array.
  1139.  
  1140.    JSON->new->allow_nonref->encode ("Hello, World!")
  1141.    => "Hello, World!"
  1142.  
  1143. =head2 allow_unknown
  1144.  
  1145.     $json = $json->allow_unknown ([$enable])
  1146.     
  1147.     $enabled = $json->get_allow_unknown
  1148.  
  1149. If $enable is true (or missing), then "encode" will *not* throw an
  1150. exception when it encounters values it cannot represent in JSON (for
  1151. example, filehandles) but instead will encode a JSON "null" value.
  1152. Note that blessed objects are not included here and are handled
  1153. separately by c<allow_nonref>.
  1154.  
  1155. If $enable is false (the default), then "encode" will throw an
  1156. exception when it encounters anything it cannot encode as JSON.
  1157.  
  1158. This option does not affect "decode" in any way, and it is
  1159. recommended to leave it off unless you know your communications
  1160. partner.
  1161.  
  1162. =head2 allow_blessed
  1163.  
  1164.     $json = $json->allow_blessed([$enable])
  1165.     
  1166.     $enabled = $json->get_allow_blessed
  1167.  
  1168. If C<$enable> is true (or missing), then the C<encode> method will not
  1169. barf when it encounters a blessed reference. Instead, the value of the
  1170. B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
  1171. disabled or no C<TO_JSON> method found) or a representation of the
  1172. object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
  1173. encoded. Has no effect on C<decode>.
  1174.  
  1175. If C<$enable> is false (the default), then C<encode> will throw an
  1176. exception when it encounters a blessed object.
  1177.  
  1178.  
  1179. =head2 convert_blessed
  1180.  
  1181.     $json = $json->convert_blessed([$enable])
  1182.     
  1183.     $enabled = $json->get_convert_blessed
  1184.  
  1185. If C<$enable> is true (or missing), then C<encode>, upon encountering a
  1186. blessed object, will check for the availability of the C<TO_JSON> method
  1187. on the object's class. If found, it will be called in scalar context
  1188. and the resulting scalar will be encoded instead of the object. If no
  1189. C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
  1190. to do.
  1191.  
  1192. The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
  1193. returns other blessed objects, those will be handled in the same
  1194. way. C<TO_JSON> must take care of not causing an endless recursion cycle
  1195. (== crash) in this case. The name of C<TO_JSON> was chosen because other
  1196. methods called by the Perl core (== not by the user of the object) are
  1197. usually in upper case letters and to avoid collisions with the C<to_json>
  1198. function or method.
  1199.  
  1200. This setting does not yet influence C<decode> in any way.
  1201.  
  1202. If C<$enable> is false, then the C<allow_blessed> setting will decide what
  1203. to do when a blessed object is found.
  1204.  
  1205. =over
  1206.  
  1207. =item convert_blessed_universally mode
  1208.  
  1209. If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
  1210. subroutine is defined as the below code:
  1211.  
  1212.    *UNIVERSAL::TO_JSON = sub {
  1213.        my $b_obj = B::svref_2object( $_[0] );
  1214.        return    $b_obj->isa('B::HV') ? { %{ $_[0] } }
  1215.                : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
  1216.                : undef
  1217.                ;
  1218.    }
  1219.  
  1220. This will cause that C<encode> method converts simple blessed objects into
  1221. JSON objects as non-blessed object.
  1222.  
  1223.    JSON -convert_blessed_universally;
  1224.    $json->allow_blessed->convert_blessed->encode( $blessed_object )
  1225.  
  1226. This feature is experimental and may be removed in the future.
  1227.  
  1228. =back
  1229.  
  1230. =head2 filter_json_object
  1231.  
  1232.     $json = $json->filter_json_object([$coderef])
  1233.  
  1234. When C<$coderef> is specified, it will be called from C<decode> each
  1235. time it decodes a JSON object. The only argument passed to the coderef
  1236. is a reference to the newly-created hash. If the code references returns
  1237. a single scalar (which need not be a reference), this value
  1238. (i.e. a copy of that scalar to avoid aliasing) is inserted into the
  1239. deserialised data structure. If it returns an empty list
  1240. (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
  1241. hash will be inserted. This setting can slow down decoding considerably.
  1242.  
  1243. When C<$coderef> is omitted or undefined, any existing callback will
  1244. be removed and C<decode> will not change the deserialised hash in any
  1245. way.
  1246.  
  1247. Example, convert all JSON objects into the integer 5:
  1248.  
  1249.    my $js = JSON->new->filter_json_object (sub { 5 });
  1250.    # returns [5]
  1251.    $js->decode ('[{}]'); # the given subroutine takes a hash reference.
  1252.    # throw an exception because allow_nonref is not enabled
  1253.    # so a lone 5 is not allowed.
  1254.    $js->decode ('{"a":1, "b":2}');
  1255.  
  1256.  
  1257. =head2 filter_json_single_key_object
  1258.  
  1259.     $json = $json->filter_json_single_key_object($key [=> $coderef])
  1260.  
  1261. Works remotely similar to C<filter_json_object>, but is only called for
  1262. JSON objects having a single key named C<$key>.
  1263.  
  1264. This C<$coderef> is called before the one specified via
  1265. C<filter_json_object>, if any. It gets passed the single value in the JSON
  1266. object. If it returns a single value, it will be inserted into the data
  1267. structure. If it returns nothing (not even C<undef> but the empty list),
  1268. the callback from C<filter_json_object> will be called next, as if no
  1269. single-key callback were specified.
  1270.  
  1271. If C<$coderef> is omitted or undefined, the corresponding callback will be
  1272. disabled. There can only ever be one callback for a given key.
  1273.  
  1274. As this callback gets called less often then the C<filter_json_object>
  1275. one, decoding speed will not usually suffer as much. Therefore, single-key
  1276. objects make excellent targets to serialise Perl objects into, especially
  1277. as single-key JSON objects are as close to the type-tagged value concept
  1278. as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
  1279. support this in any way, so you need to make sure your data never looks
  1280. like a serialised Perl hash.
  1281.  
  1282. Typical names for the single object key are C<__class_whatever__>, or
  1283. C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
  1284. things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
  1285. with real hashes.
  1286.  
  1287. Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
  1288. into the corresponding C<< $WIDGET{<id>} >> object:
  1289.  
  1290.    # return whatever is in $WIDGET{5}:
  1291.    JSON
  1292.       ->new
  1293.       ->filter_json_single_key_object (__widget__ => sub {
  1294.             $WIDGET{ $_[0] }
  1295.          })
  1296.       ->decode ('{"__widget__": 5')
  1297.  
  1298.    # this can be used with a TO_JSON method in some "widget" class
  1299.    # for serialisation to json:
  1300.    sub WidgetBase::TO_JSON {
  1301.       my ($self) = @_;
  1302.  
  1303.       unless ($self->{id}) {
  1304.          $self->{id} = ..get..some..id..;
  1305.          $WIDGET{$self->{id}} = $self;
  1306.       }
  1307.  
  1308.       { __widget__ => $self->{id} }
  1309.    }
  1310.  
  1311.  
  1312. =head2 shrink
  1313.  
  1314.     $json = $json->shrink([$enable])
  1315.     
  1316.     $enabled = $json->get_shrink
  1317.  
  1318. With JSON::XS, this flag resizes strings generated by either
  1319. C<encode> or C<decode> to their minimum size possible. This can save
  1320. memory when your JSON texts are either very very long or you have many
  1321. short strings. It will also try to downgrade any strings to octet-form
  1322. if possible: perl stores strings internally either in an encoding called
  1323. UTF-X or in octet-form. The latter cannot store everything but uses less
  1324. space in general (and some buggy Perl or C code might even rely on that
  1325. internal representation being used).
  1326.  
  1327. With JSON::PP, it is noop about resizing strings but tries
  1328. C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
  1329.  
  1330. See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
  1331.  
  1332. =head2 max_depth
  1333.  
  1334.     $json = $json->max_depth([$maximum_nesting_depth])
  1335.     
  1336.     $max_depth = $json->get_max_depth
  1337.  
  1338. Sets the maximum nesting level (default C<512>) accepted while encoding
  1339. or decoding. If a higher nesting level is detected in JSON text or a Perl
  1340. data structure, then the encoder and decoder will stop and croak at that
  1341. point.
  1342.  
  1343. Nesting level is defined by number of hash- or arrayrefs that the encoder
  1344. needs to traverse to reach a given point or the number of C<{> or C<[>
  1345. characters without their matching closing parenthesis crossed to reach a
  1346. given character in a string.
  1347.  
  1348. If no argument is given, the highest possible setting will be used, which
  1349. is rarely useful.
  1350.  
  1351. Note that nesting is implemented by recursion in C. The default value has
  1352. been chosen to be as large as typical operating systems allow without
  1353. crashing. (JSON::XS)
  1354.  
  1355. With JSON::PP as the backend, when a large value (100 or more) was set and
  1356. it de/encodes a deep nested object/text, it may raise a warning
  1357. 'Deep recursion on subroutin' at the perl runtime phase.
  1358.  
  1359. See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
  1360.  
  1361. =head2 max_size
  1362.  
  1363.     $json = $json->max_size([$maximum_string_size])
  1364.     
  1365.     $max_size = $json->get_max_size
  1366.  
  1367. Set the maximum length a JSON text may have (in bytes) where decoding is
  1368. being attempted. The default is C<0>, meaning no limit. When C<decode>
  1369. is called on a string that is longer then this many bytes, it will not
  1370. attempt to decode the string but throw an exception. This setting has no
  1371. effect on C<encode> (yet).
  1372.  
  1373. If no argument is given, the limit check will be deactivated (same as when
  1374. C<0> is specified).
  1375.  
  1376. See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
  1377.  
  1378. =head2 encode
  1379.  
  1380.     $json_text = $json->encode($perl_scalar)
  1381.  
  1382. Converts the given Perl data structure (a simple scalar or a reference
  1383. to a hash or array) to its JSON representation. Simple scalars will be
  1384. converted into JSON string or number sequences, while references to arrays
  1385. become JSON arrays and references to hashes become JSON objects. Undefined
  1386. Perl values (e.g. C<undef>) become JSON C<null> values.
  1387. References to the integers C<0> and C<1> are converted into C<true> and C<false>.
  1388.  
  1389. =head2 decode
  1390.  
  1391.     $perl_scalar = $json->decode($json_text)
  1392.  
  1393. The opposite of C<encode>: expects a JSON text and tries to parse it,
  1394. returning the resulting simple scalar or reference. Croaks on error.
  1395.  
  1396. JSON numbers and strings become simple Perl scalars. JSON arrays become
  1397. Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
  1398. C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
  1399. C<null> becomes C<undef>.
  1400.  
  1401. =head2 decode_prefix
  1402.  
  1403.     ($perl_scalar, $characters) = $json->decode_prefix($json_text)
  1404.  
  1405. This works like the C<decode> method, but instead of raising an exception
  1406. when there is trailing garbage after the first JSON object, it will
  1407. silently stop parsing there and return the number of characters consumed
  1408. so far.
  1409.  
  1410.    JSON->new->decode_prefix ("[1] the tail")
  1411.    => ([], 3)
  1412.  
  1413. See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
  1414.  
  1415. =head2 property
  1416.  
  1417.     $boolean = $json->property($property_name)
  1418.  
  1419. Returns a boolean value about above some properties.
  1420.  
  1421. The available properties are C<ascii>, C<latin1>, C<utf8>,
  1422. C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
  1423. C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
  1424. C<shrink>, C<max_depth> and C<max_size>.
  1425.  
  1426.    $boolean = $json->property('utf8');
  1427.     => 0
  1428.    $json->utf8;
  1429.    $boolean = $json->property('utf8');
  1430.     => 1
  1431.  
  1432. Sets the property with a given boolean value.
  1433.  
  1434.     $json = $json->property($property_name => $boolean);
  1435.  
  1436. With no argumnt, it returns all the above properties as a hash reference.
  1437.  
  1438.     $flag_hashref = $json->property();
  1439.  
  1440. =head1 INCREMENTAL PARSING
  1441.  
  1442. Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
  1443.  
  1444. In some cases, there is the need for incremental parsing of JSON texts.
  1445. This module does allow you to parse a JSON stream incrementally.
  1446. It does so by accumulating text until it has a full JSON object, which
  1447. it then can decode. This process is similar to using C<decode_prefix>
  1448. to see if a full JSON object is available, but is much more efficient
  1449. (and can be implemented with a minimum of method calls).
  1450.  
  1451. The backend module will only attempt to parse the JSON text once it is sure it
  1452. has enough text to get a decisive result, using a very simple but
  1453. truly incremental parser. This means that it sometimes won't stop as
  1454. early as the full parser, for example, it doesn't detect parenthese
  1455. mismatches. The only thing it guarantees is that it starts decoding as
  1456. soon as a syntactically valid JSON text has been seen. This means you need
  1457. to set resource limits (e.g. C<max_size>) to ensure the parser will stop
  1458. parsing in the presence if syntax errors.
  1459.  
  1460. The following methods implement this incremental parser.
  1461.  
  1462. =head2 incr_parse
  1463.  
  1464.     $json->incr_parse( [$string] ) # void context
  1465.     
  1466.     $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
  1467.     
  1468.     @obj_or_empty = $json->incr_parse( [$string] ) # list context
  1469.  
  1470. This is the central parsing function. It can both append new text and
  1471. extract objects from the stream accumulated so far (both of these
  1472. functions are optional).
  1473.  
  1474. If C<$string> is given, then this string is appended to the already
  1475. existing JSON fragment stored in the C<$json> object.
  1476.  
  1477. After that, if the function is called in void context, it will simply
  1478. return without doing anything further. This can be used to add more text
  1479. in as many chunks as you want.
  1480.  
  1481. If the method is called in scalar context, then it will try to extract
  1482. exactly I<one> JSON object. If that is successful, it will return this
  1483. object, otherwise it will return C<undef>. If there is a parse error,
  1484. this method will croak just as C<decode> would do (one can then use
  1485. C<incr_skip> to skip the errornous part). This is the most common way of
  1486. using the method.
  1487.  
  1488. And finally, in list context, it will try to extract as many objects
  1489. from the stream as it can find and return them, or the empty list
  1490. otherwise. For this to work, there must be no separators between the JSON
  1491. objects or arrays, instead they must be concatenated back-to-back. If
  1492. an error occurs, an exception will be raised as in the scalar context
  1493. case. Note that in this case, any previously-parsed JSON texts will be
  1494. lost.
  1495.  
  1496. Example: Parse some JSON arrays/objects in a given string and return them.
  1497.  
  1498.     my @objs = JSON->new->incr_parse ("[5][7][1,2]");
  1499.  
  1500. =head2 incr_text
  1501.  
  1502.     $lvalue_string = $json->incr_text
  1503.  
  1504. This method returns the currently stored JSON fragment as an lvalue, that
  1505. is, you can manipulate it. This I<only> works when a preceding call to
  1506. C<incr_parse> in I<scalar context> successfully returned an object. Under
  1507. all other circumstances you must not call this function (I mean it.
  1508. although in simple tests it might actually work, it I<will> fail under
  1509. real world conditions). As a special exception, you can also call this
  1510. method before having parsed anything.
  1511.  
  1512. This function is useful in two cases: a) finding the trailing text after a
  1513. JSON object or b) parsing multiple JSON objects separated by non-JSON text
  1514. (such as commas).
  1515.  
  1516.     $json->incr_text =~ s/\s*,\s*//;
  1517.  
  1518. In Perl 5.005, C<lvalue> attribute is not available.
  1519. You must write codes like the below:
  1520.  
  1521.     $string = $json->incr_text;
  1522.     $string =~ s/\s*,\s*//;
  1523.     $json->incr_text( $string );
  1524.  
  1525. =head2 incr_skip
  1526.  
  1527.     $json->incr_skip
  1528.  
  1529. This will reset the state of the incremental parser and will remove the
  1530. parsed text from the input buffer. This is useful after C<incr_parse>
  1531. died, in which case the input buffer and incremental parser state is left
  1532. unchanged, to skip the text parsed so far and to reset the parse state.
  1533.  
  1534. =head2 incr_reset
  1535.  
  1536.     $json->incr_reset
  1537.  
  1538. This completely resets the incremental parser, that is, after this call,
  1539. it will be as if the parser had never parsed anything.
  1540.  
  1541. This is useful if you want ot repeatedly parse JSON objects and want to
  1542. ignore any trailing data, which means you have to reset the parser after
  1543. each successful decode.
  1544.  
  1545. See to L<JSON::XS/INCREMENTAL PARSING> for examples.
  1546.  
  1547.  
  1548. =head1 JSON::PP SUPPORT METHODS
  1549.  
  1550. The below methods are JSON::PP own methods, so when C<JSON> works
  1551. with JSON::PP (i.e. the created object is a JSON::PP object), available.
  1552. See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
  1553.  
  1554. If you use C<JSON> with additonal C<-support_by_pp>, some methods
  1555. are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
  1556.  
  1557.    BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
  1558.    
  1559.    use JSON -support_by_pp;
  1560.    
  1561.    my $json = new JSON;
  1562.    $json->allow_nonref->escape_slash->encode("/");
  1563.  
  1564.    # functional interfaces too.
  1565.    print to_json(["/"], {escape_slash => 1});
  1566.    print from_json('["foo"]', {utf8 => 1});
  1567.  
  1568. If you do not want to all functions but C<-support_by_pp>,
  1569. use C<-no_export>.
  1570.  
  1571.    use JSON -support_by_pp, -no_export;
  1572.    # functional interfaces are not exported.
  1573.  
  1574. =head2 allow_singlequote
  1575.  
  1576.     $json = $json->allow_singlequote([$enable])
  1577.  
  1578. If C<$enable> is true (or missing), then C<decode> will accept
  1579. any JSON strings quoted by single quotations that are invalid JSON
  1580. format.
  1581.  
  1582.     $json->allow_singlequote->decode({"foo":'bar'});
  1583.     $json->allow_singlequote->decode({'foo':"bar"});
  1584.     $json->allow_singlequote->decode({'foo':'bar'});
  1585.  
  1586. As same as the C<relaxed> option, this option may be used to parse
  1587. application-specific files written by humans.
  1588.  
  1589. =head2 allow_barekey
  1590.  
  1591.     $json = $json->allow_barekey([$enable])
  1592.  
  1593. If C<$enable> is true (or missing), then C<decode> will accept
  1594. bare keys of JSON object that are invalid JSON format.
  1595.  
  1596. As same as the C<relaxed> option, this option may be used to parse
  1597. application-specific files written by humans.
  1598.  
  1599.     $json->allow_barekey->decode('{foo:"bar"}');
  1600.  
  1601. =head2 allow_bignum
  1602.  
  1603.     $json = $json->allow_bignum([$enable])
  1604.  
  1605. If C<$enable> is true (or missing), then C<decode> will convert
  1606. the big integer Perl cannot handle as integer into a L<Math::BigInt>
  1607. object and convert a floating number (any) into a L<Math::BigFloat>.
  1608.  
  1609. On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  1610. objects into JSON numbers with C<allow_blessed> enable.
  1611.  
  1612.    $json->allow_nonref->allow_blessed->allow_bignum;
  1613.    $bigfloat = $json->decode('2.000000000000000000000000001');
  1614.    print $json->encode($bigfloat);
  1615.    # => 2.000000000000000000000000001
  1616.  
  1617. See to L<MAPPING> aboout the conversion of JSON number.
  1618.  
  1619. =head2 loose
  1620.  
  1621.     $json = $json->loose([$enable])
  1622.  
  1623. The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
  1624. and the module doesn't allow to C<decode> to these (except for \x2f).
  1625. If C<$enable> is true (or missing), then C<decode>  will accept these
  1626. unescaped strings.
  1627.  
  1628.     $json->loose->decode(qq|["abc
  1629.                                    def"]|);
  1630.  
  1631. See to L<JSON::PP/JSON::PP OWN METHODS>.
  1632.  
  1633. =head2 escape_slash
  1634.  
  1635.     $json = $json->escape_slash([$enable])
  1636.  
  1637. According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
  1638. JSON backend modules encode strings without escaping slash.
  1639.  
  1640. If C<$enable> is true (or missing), then C<encode> will escape slashes.
  1641.  
  1642. =head2 indent_length
  1643.  
  1644.     $json = $json->indent_length($length)
  1645.  
  1646. With JSON::XS, The indent space length is 3 and cannot be changed.
  1647. With JSON::PP, it sets the indent space length with the given $length.
  1648. The default is 3. The acceptable range is 0 to 15.
  1649.  
  1650. =head2 sort_by
  1651.  
  1652.     $json = $json->sort_by($function_name)
  1653.     $json = $json->sort_by($subroutine_ref)
  1654.  
  1655. If $function_name or $subroutine_ref are set, its sort routine are used.
  1656.  
  1657.    $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
  1658.    # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  1659.  
  1660.    $js = $pc->sort_by('own_sort')->encode($obj);
  1661.    # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  1662.  
  1663.    sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
  1664.  
  1665. As the sorting routine runs in the JSON::PP scope, the given
  1666. subroutine name and the special variables C<$a>, C<$b> will begin
  1667. with 'JSON::PP::'.
  1668.  
  1669. If $integer is set, then the effect is same as C<canonical> on.
  1670.  
  1671. See to L<JSON::PP/JSON::PP OWN METHODS>.
  1672.  
  1673. =head1 MAPPING
  1674.  
  1675. This section is copied from JSON::XS and modified to C<JSON>.
  1676. JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
  1677.  
  1678. See to L<JSON::XS/MAPPING>.
  1679.  
  1680. =head2 JSON -> PERL
  1681.  
  1682. =over 4
  1683.  
  1684. =item object
  1685.  
  1686. A JSON object becomes a reference to a hash in Perl. No ordering of object
  1687. keys is preserved (JSON does not preserver object key ordering itself).
  1688.  
  1689. =item array
  1690.  
  1691. A JSON array becomes a reference to an array in Perl.
  1692.  
  1693. =item string
  1694.  
  1695. A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
  1696. are represented by the same codepoints in the Perl string, so no manual
  1697. decoding is necessary.
  1698.  
  1699. =item number
  1700.  
  1701. A JSON number becomes either an integer, numeric (floating point) or
  1702. string scalar in perl, depending on its range and any fractional parts. On
  1703. the Perl level, there is no difference between those as Perl handles all
  1704. the conversion details, but an integer may take slightly less memory and
  1705. might represent more values exactly than floating point numbers.
  1706.  
  1707. If the number consists of digits only, C<JSON> will try to represent
  1708. it as an integer value. If that fails, it will try to represent it as
  1709. a numeric (floating point) value if that is possible without loss of
  1710. precision. Otherwise it will preserve the number as a string value (in
  1711. which case you lose roundtripping ability, as the JSON number will be
  1712. re-encoded toa JSON string).
  1713.  
  1714. Numbers containing a fractional or exponential part will always be
  1715. represented as numeric (floating point) values, possibly at a loss of
  1716. precision (in which case you might lose perfect roundtripping ability, but
  1717. the JSON number will still be re-encoded as a JSON number).
  1718.  
  1719. Note that precision is not accuracy - binary floating point values cannot
  1720. represent most decimal fractions exactly, and when converting from and to
  1721. floating point, C<JSON> only guarantees precision up to but not including
  1722. the leats significant bit.
  1723.  
  1724. If the backend is JSON::PP and C<allow_bignum> is enable, the big integers 
  1725. and the numeric can be optionally converted into L<Math::BigInt> and
  1726. L<Math::BigFloat> objects.
  1727.  
  1728. =item true, false
  1729.  
  1730. These JSON atoms become C<JSON::true> and C<JSON::false>,
  1731. respectively. They are overloaded to act almost exactly like the numbers
  1732. C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
  1733. the C<JSON::is_bool> function.
  1734.  
  1735. If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
  1736. they represent as C<true> and C<false> respectively.
  1737.  
  1738.    print JSON::true . "\n";
  1739.     => true
  1740.    print JSON::true + 1;
  1741.     => 1
  1742.  
  1743.    ok(JSON::true eq 'true');
  1744.    ok(JSON::true eq  '1');
  1745.    ok(JSON::true == 1);
  1746.  
  1747. C<JSON> will install these missing overloading features to the backend modules.
  1748.  
  1749.  
  1750. =item null
  1751.  
  1752. A JSON null atom becomes C<undef> in Perl.
  1753.  
  1754. C<JSON::null> returns C<unddef>.
  1755.  
  1756. =back
  1757.  
  1758.  
  1759. =head2 PERL -> JSON
  1760.  
  1761. The mapping from Perl to JSON is slightly more difficult, as Perl is a
  1762. truly typeless language, so we can only guess which JSON type is meant by
  1763. a Perl value.
  1764.  
  1765. =over 4
  1766.  
  1767. =item hash references
  1768.  
  1769. Perl hash references become JSON objects. As there is no inherent ordering
  1770. in hash keys (or JSON objects), they will usually be encoded in a
  1771. pseudo-random order that can change between runs of the same program but
  1772. stays generally the same within a single run of a program. C<JSON>
  1773. optionally sort the hash keys (determined by the I<canonical> flag), so
  1774. the same datastructure will serialise to the same JSON text (given same
  1775. settings and version of JSON::XS), but this incurs a runtime overhead
  1776. and is only rarely useful, e.g. when you want to compare some JSON text
  1777. against another for equality.
  1778.  
  1779. In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
  1780.  
  1781.  
  1782. =item array references
  1783.  
  1784. Perl array references become JSON arrays.
  1785.  
  1786. =item other references
  1787.  
  1788. Other unblessed references are generally not allowed and will cause an
  1789. exception to be thrown, except for references to the integers C<0> and
  1790. C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
  1791. also use C<JSON::false> and C<JSON::true> to improve readability.
  1792.  
  1793.    to_json [\0,JSON::true]      # yields [false,true]
  1794.  
  1795. =item JSON::true, JSON::false, JSON::null
  1796.  
  1797. These special values become JSON true and JSON false values,
  1798. respectively. You can also use C<\1> and C<\0> directly if you want.
  1799.  
  1800. JSON::null returns C<undef>.
  1801.  
  1802. =item blessed objects
  1803.  
  1804. Blessed objects are not directly representable in JSON. See the
  1805. C<allow_blessed> and C<convert_blessed> methods on various options on
  1806. how to deal with this: basically, you can choose between throwing an
  1807. exception, encoding the reference as if it weren't blessed, or provide
  1808. your own serialiser method.
  1809.  
  1810. With C<convert_blessed_universally> mode,  C<encode> converts blessed
  1811. hash references or blessed array references (contains other blessed references)
  1812. into JSON members and arrays.
  1813.  
  1814.    use JSON -convert_blessed_universally;
  1815.    JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
  1816.  
  1817. See to L<convert_blessed>.
  1818.  
  1819. =item simple scalars
  1820.  
  1821. Simple Perl scalars (any scalar that is not a reference) are the most
  1822. difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
  1823. JSON C<null> values, scalars that have last been used in a string context
  1824. before encoding as JSON strings, and anything else as number value:
  1825.  
  1826.    # dump as number
  1827.    encode_json [2]                      # yields [2]
  1828.    encode_json [-3.0e17]                # yields [-3e+17]
  1829.    my $value = 5; encode_json [$value]  # yields [5]
  1830.  
  1831.    # used as string, so dump as string
  1832.    print $value;
  1833.    encode_json [$value]                 # yields ["5"]
  1834.  
  1835.    # undef becomes null
  1836.    encode_json [undef]                  # yields [null]
  1837.  
  1838. You can force the type to be a string by stringifying it:
  1839.  
  1840.    my $x = 3.1; # some variable containing a number
  1841.    "$x";        # stringified
  1842.    $x .= "";    # another, more awkward way to stringify
  1843.    print $x;    # perl does it for you, too, quite often
  1844.  
  1845. You can force the type to be a number by numifying it:
  1846.  
  1847.    my $x = "3"; # some variable containing a string
  1848.    $x += 0;     # numify it, ensuring it will be dumped as a number
  1849.    $x *= 1;     # same thing, the choise is yours.
  1850.  
  1851. You can not currently force the type in other, less obscure, ways.
  1852.  
  1853. Note that numerical precision has the same meaning as under Perl (so
  1854. binary to decimal conversion follows the same rules as in Perl, which
  1855. can differ to other languages). Also, your perl interpreter might expose
  1856. extensions to the floating point numbers of your platform, such as
  1857. infinities or NaN's - these cannot be represented in JSON, and it is an
  1858. error to pass those in.
  1859.  
  1860. =item Big Number
  1861.  
  1862. If the backend is JSON::PP and C<allow_bignum> is enable, 
  1863. C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  1864. objects into JSON numbers.
  1865.  
  1866.  
  1867. =back
  1868.  
  1869. =head1 JSON and ECMAscript
  1870.  
  1871. See to L<JSON::XS/JSON and ECMAscript>.
  1872.  
  1873. =head1 JSON and YAML
  1874.  
  1875. JSON is not a subset of YAML.
  1876. See to L<JSON::XS/JSON and YAML>.
  1877.  
  1878.  
  1879. =head1 BACKEND MODULE DECISION
  1880.  
  1881. When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
  1882. C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
  1883.  
  1884. The C<JSON> constructor method returns an object inherited from the backend module,
  1885. and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash
  1886. reference.
  1887.  
  1888. So, your program should not depend on the backend module, especially
  1889. returned objects should not be modified.
  1890.  
  1891.  my $json = JSON->new; # XS or PP?
  1892.  $json->{stash} = 'this is xs object'; # this code may raise an error!
  1893.  
  1894. To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
  1895.  
  1896.   JSON->backend; # 'JSON::XS' or 'JSON::PP'
  1897.   
  1898.   JSON->backend->is_pp: # 0 or 1
  1899.   
  1900.   JSON->backend->is_xs: # 1 or 0
  1901.   
  1902.   $json->is_xs; # 1 or 0
  1903.   
  1904.   $json->is_pp; # 0 or 1
  1905.  
  1906.  
  1907. If you set an enviornment variable C<PERL_JSON_BACKEND>, The calling action will be changed.
  1908.  
  1909. =over
  1910.  
  1911. =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
  1912.  
  1913. Always use JSON::PP
  1914.  
  1915. =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
  1916.  
  1917. (The default) Use compiled JSON::XS if it is properly compiled & installed,
  1918. otherwise use JSON::PP.
  1919.  
  1920. =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
  1921.  
  1922. Always use compiled JSON::XS, die if it isn't properly compiled & installed.
  1923.  
  1924. =back
  1925.  
  1926. These ideas come from L<DBI::PurePerl> mechanism.
  1927.  
  1928. example:
  1929.  
  1930.  BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
  1931.  use JSON; # always uses JSON::PP
  1932.  
  1933. In future, it may be able to specify another module.
  1934.  
  1935. =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
  1936.  
  1937. Many methods are available with either JSON::XS or JSON::PP and
  1938. when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported)
  1939. method is called, it will C<warn> and be noop.
  1940.  
  1941. But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
  1942. it makes a part of those unupported methods available.
  1943. This feature is achieved by using JSON::PP in C<de/encode>.
  1944.  
  1945.    BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
  1946.    use JSON -support_by_pp;
  1947.    my $json = new JSON;
  1948.    $json->allow_nonref->escape_slash->encode("/");
  1949.  
  1950. At this time, the returned object is a C<JSON::Backend::XS::Supportable>
  1951. object (re-blessed XS object), and  by checking JSON::XS unsupported flags
  1952. in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
  1953. C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
  1954.  
  1955. When any unsupported methods are not enable, C<XS de/encode> will be
  1956. used as is. The switch is achieved by changing the symbolic tables.
  1957.  
  1958. C<-support_by_pp> is effective only when the backend module is JSON::XS
  1959. and it makes the de/encoding speed down a bit.
  1960.  
  1961. See to L<JSON::PP SUPPORT METHODS>.
  1962.  
  1963. =head1 INCOMPATIBLE CHANGES TO OLD VERSION
  1964.  
  1965. There are big incompatibility between new version (2.00) and old (1.xx).
  1966. If you use old C<JSON> 1.xx in your code, please check it.
  1967.  
  1968. See to L<Transition ways from 1.xx to 2.xx.>
  1969.  
  1970. =over
  1971.  
  1972. =item jsonToObj and objToJson are obsoleted.
  1973.  
  1974. Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
  1975. (but not yet deleted from the source).
  1976. If you use these functions in your code, please replace them
  1977. with C<from_json> and C<to_json>.
  1978.  
  1979.  
  1980. =item Global variables are no longer available.
  1981.  
  1982. C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
  1983. - are not available any longer.
  1984. Instead, various features can be used through object methods.
  1985.  
  1986.  
  1987. =item Package JSON::Converter and JSON::Parser are deleted.
  1988.  
  1989. Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
  1990.  
  1991. =item Package JSON::NotString is deleted.
  1992.  
  1993. There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
  1994. and numbers. It was deleted and replaced by C<JSON::Boolean>.
  1995.  
  1996. C<JSON::Boolean> represents C<true> and C<false>.
  1997.  
  1998. C<JSON::Boolean> does not represent C<null>.
  1999.  
  2000. C<JSON::null> returns C<undef>.
  2001.  
  2002. C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
  2003. to L<JSON::Boolean>.
  2004.  
  2005. =item function JSON::Number is obsoleted.
  2006.  
  2007. C<JSON::Number> is now needless because JSON::XS and JSON::PP have
  2008. round-trip integrity.
  2009.  
  2010. =item JSONRPC modules are deleted.
  2011.  
  2012. Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
  2013. and C<Apache::JSONRPC > are deleted in this distribution.
  2014. Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
  2015.  
  2016. =back
  2017.  
  2018. =head2 Transition ways from 1.xx to 2.xx.
  2019.  
  2020. You should set C<suport_by_pp> mode firstly, because
  2021. it is always successful for the below codes even with JSON::XS.
  2022.  
  2023.     use JSON -support_by_pp;
  2024.  
  2025. =over
  2026.  
  2027. =item Exported jsonToObj (simple)
  2028.  
  2029.   from_json($json_text);
  2030.  
  2031. =item Exported objToJson (simple)
  2032.  
  2033.   to_json($perl_scalar);
  2034.  
  2035. =item Exported jsonToObj (advanced)
  2036.  
  2037.   $flags = {allow_barekey => 1, allow_singlequote => 1};
  2038.   from_json($json_text, $flags);
  2039.  
  2040. equivalent to:
  2041.  
  2042.   $JSON::BareKey = 1;
  2043.   $JSON::QuotApos = 1;
  2044.   jsonToObj($json_text);
  2045.  
  2046. =item Exported objToJson (advanced)
  2047.  
  2048.   $flags = {allow_blessed => 1, allow_barekey => 1};
  2049.   to_json($perl_scalar, $flags);
  2050.  
  2051. equivalent to:
  2052.  
  2053.   $JSON::BareKey = 1;
  2054.   objToJson($perl_scalar);
  2055.  
  2056. =item jsonToObj as object method
  2057.  
  2058.   $json->decode($json_text);
  2059.  
  2060. =item objToJson as object method
  2061.  
  2062.   $json->encode($perl_scalar);
  2063.  
  2064. =item new method with parameters
  2065.  
  2066. The C<new> method in 2.x takes any parameters no longer.
  2067. You can set parameters instead;
  2068.  
  2069.    $json = JSON->new->pretty;
  2070.  
  2071. =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
  2072.  
  2073. If C<indent> is enable, that menas C<$JSON::Pretty> flag set. And
  2074. C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
  2075. In conclusion:
  2076.  
  2077.    $json->indent->space_before->space_after;
  2078.  
  2079. Equivalent to:
  2080.  
  2081.   $json->pretty;
  2082.  
  2083. To change indent length, use C<indent_length>.
  2084.  
  2085. (Only with JSON::PP, if C<-support_by_pp> is not used.)
  2086.  
  2087.   $json->pretty->indent_length(2)->encode($perl_scalar);
  2088.  
  2089. =item $JSON::BareKey
  2090.  
  2091. (Only with JSON::PP, if C<-support_by_pp> is not used.)
  2092.  
  2093.   $json->allow_barekey->decode($json_text)
  2094.  
  2095. =item $JSON::ConvBlessed
  2096.  
  2097. use C<-convert_blessed_universally>. See to L<convert_blessed>.
  2098.  
  2099. =item $JSON::QuotApos
  2100.  
  2101. (Only with JSON::PP, if C<-support_by_pp> is not used.)
  2102.  
  2103.   $json->allow_singlequote->decode($json_text)
  2104.  
  2105. =item $JSON::SingleQuote
  2106.  
  2107. Disable. C<JSON> does not make such a invalid JSON string any longer.
  2108.  
  2109. =item $JSON::KeySort
  2110.  
  2111.   $json->canonical->encode($perl_scalar)
  2112.  
  2113. This is the ascii sort.
  2114.  
  2115. If you want to use with your own sort routine, check the C<sort_by> method.
  2116.  
  2117. (Only with JSON::PP, even if C<-support_by_pp> is used currently.)
  2118.  
  2119.   $json->sort_by($sort_routine_ref)->encode($perl_scalar)
  2120.  
  2121.   $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
  2122.  
  2123. Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
  2124.  
  2125. =item $JSON::SkipInvalid
  2126.  
  2127.   $json->allow_unknown
  2128.  
  2129. =item $JSON::AUTOCONVERT
  2130.  
  2131. Needless. C<JSON> backend modules have the round-trip integrity.
  2132.  
  2133. =item $JSON::UTF8
  2134.  
  2135. Needless because C<JSON> (JSON::XS/JSON::PP) sets
  2136. the UTF8 flag on properly.
  2137.  
  2138.     # With UTF8-flagged strings
  2139.  
  2140.     $json->allow_nonref;
  2141.     $str = chr(1000); # UTF8-flagged
  2142.  
  2143.     $json_text  = $json->utf8(0)->encode($str);
  2144.     utf8::is_utf8($json_text);
  2145.     # true
  2146.     $json_text  = $json->utf8(1)->encode($str);
  2147.     utf8::is_utf8($json_text);
  2148.     # false
  2149.  
  2150.     $str = '"' . chr(1000) . '"'; # UTF8-flagged
  2151.  
  2152.     $perl_scalar  = $json->utf8(0)->decode($str);
  2153.     utf8::is_utf8($perl_scalar);
  2154.     # true
  2155.     $perl_scalar  = $json->utf8(1)->decode($str);
  2156.     # died because of 'Wide character in subroutine'
  2157.  
  2158. See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
  2159.  
  2160. =item $JSON::UnMapping
  2161.  
  2162. Disable. See to L<MAPPING>.
  2163.  
  2164. =item $JSON::SelfConvert
  2165.  
  2166. This option was deleted.
  2167. Instead of it, if a givien blessed object has the C<TO_JSON> method,
  2168. C<TO_JSON> will be executed with C<convert_blessed>.
  2169.  
  2170.   $json->convert_blessed->encode($bleesed_hashref_or_arrayref)
  2171.   # if need, call allow_blessed
  2172.  
  2173. Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
  2174.  
  2175. =back
  2176.  
  2177. =head1 TODO
  2178.  
  2179. =over
  2180.  
  2181. =item example programs
  2182.  
  2183. =back
  2184.  
  2185. =head1 THREADS
  2186.  
  2187. No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
  2188.  
  2189.  
  2190. =head1 BUGS
  2191.  
  2192. Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
  2193.  
  2194.  
  2195. =head1 SEE ALSO
  2196.  
  2197. Most of the document is copied and modified from JSON::XS doc.
  2198.  
  2199. L<JSON::XS>, L<JSON::PP>
  2200.  
  2201. C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
  2202.  
  2203. =head1 AUTHOR
  2204.  
  2205. Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  2206.  
  2207. JSON::XS was written by  Marc Lehmann <schmorp[at]schmorp.de>
  2208.  
  2209. The relese of this new version owes to the courtesy of Marc Lehmann.
  2210.  
  2211.  
  2212. =head1 COPYRIGHT AND LICENSE
  2213.  
  2214. Copyright 2005-2010 by Makamaka Hannyaharamitu
  2215.  
  2216. This library is free software; you can redistribute it and/or modify
  2217. it under the same terms as Perl itself. 
  2218.  
  2219. =cut
  2220.  
  2221.