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 / PP.pm next >
Encoding:
Perl POD Document  |  2010-04-01  |  58.8 KB  |  2,197 lines

  1. package JSON::PP;
  2.  
  3. # JSON-2.0
  4.  
  5. use 5.005;
  6. use strict;
  7. use base qw(Exporter);
  8. use overload;
  9.  
  10. use Carp ();
  11. use B ();
  12. #use Devel::Peek;
  13.  
  14. $JSON::PP::VERSION = '2.27003';
  15.  
  16. @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
  17.  
  18. # instead of hash-access, i tried index-access for speed.
  19. # but this method is not faster than what i expected. so it will be changed.
  20.  
  21. use constant P_ASCII                => 0;
  22. use constant P_LATIN1               => 1;
  23. use constant P_UTF8                 => 2;
  24. use constant P_INDENT               => 3;
  25. use constant P_CANONICAL            => 4;
  26. use constant P_SPACE_BEFORE         => 5;
  27. use constant P_SPACE_AFTER          => 6;
  28. use constant P_ALLOW_NONREF         => 7;
  29. use constant P_SHRINK               => 8;
  30. use constant P_ALLOW_BLESSED        => 9;
  31. use constant P_CONVERT_BLESSED      => 10;
  32. use constant P_RELAXED              => 11;
  33.  
  34. use constant P_LOOSE                => 12;
  35. use constant P_ALLOW_BIGNUM         => 13;
  36. use constant P_ALLOW_BAREKEY        => 14;
  37. use constant P_ALLOW_SINGLEQUOTE    => 15;
  38. use constant P_ESCAPE_SLASH         => 16;
  39. use constant P_AS_NONBLESSED        => 17;
  40.  
  41. use constant P_ALLOW_UNKNOWN        => 18;
  42.  
  43. BEGIN {
  44.     my @xs_compati_bit_properties = qw(
  45.             latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
  46.             allow_blessed convert_blessed relaxed allow_unknown
  47.     );
  48.     my @pp_bit_properties = qw(
  49.             allow_singlequote allow_bignum loose
  50.             allow_barekey escape_slash as_nonblessed
  51.     );
  52.  
  53.     # Perl version check, Unicode handling is enable?
  54.     # Helper module sets @JSON::PP::_properties.
  55.  
  56.     my $helper = $] >= 5.008 ? 'JSON::PP58'
  57.                : $] >= 5.006 ? 'JSON::PP56'
  58.                :               'JSON::PP5005'
  59.                ;
  60.  
  61.     eval qq| require $helper |;
  62.     if ($@) { Carp::croak $@; }
  63.  
  64.     for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
  65.         my $flag_name = 'P_' . uc($name);
  66.  
  67.         eval qq/
  68.             sub $name {
  69.                 my \$enable = defined \$_[1] ? \$_[1] : 1;
  70.  
  71.                 if (\$enable) {
  72.                     \$_[0]->{PROPS}->[$flag_name] = 1;
  73.                 }
  74.                 else {
  75.                     \$_[0]->{PROPS}->[$flag_name] = 0;
  76.                 }
  77.  
  78.                 \$_[0];
  79.             }
  80.  
  81.             sub get_$name {
  82.                 \$_[0]->{PROPS}->[$flag_name] ? 1 : '';
  83.             }
  84.         /;
  85.     }
  86.  
  87. }
  88.  
  89.  
  90.  
  91. # Functions
  92.  
  93. my %encode_allow_method
  94.      = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash
  95.                           allow_blessed convert_blessed indent indent_length allow_bignum
  96.                           as_nonblessed
  97.                         /;
  98. my %decode_allow_method
  99.      = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum
  100.                           allow_barekey max_size relaxed/;
  101.  
  102.  
  103. my $JSON; # cache
  104.  
  105. sub encode_json ($) { # encode
  106.     ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
  107. }
  108.  
  109.  
  110. sub decode_json { # decode
  111.     ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
  112. }
  113.  
  114. # Obsoleted
  115.  
  116. sub to_json($) {
  117.    Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
  118. }
  119.  
  120.  
  121. sub from_json($) {
  122.    Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
  123. }
  124.  
  125.  
  126. # Methods
  127.  
  128. sub new {
  129.     my $class = shift;
  130.     my $self  = {
  131.         max_depth   => 512,
  132.         max_size    => 0,
  133.         indent      => 0,
  134.         FLAGS       => 0,
  135.         fallback      => sub { encode_error('Invalid value. JSON can only reference.') },
  136.         indent_length => 3,
  137.     };
  138.  
  139.     bless $self, $class;
  140. }
  141.  
  142.  
  143. sub encode {
  144.     return $_[0]->PP_encode_json($_[1]);
  145. }
  146.  
  147.  
  148. sub decode {
  149.     return $_[0]->PP_decode_json($_[1], 0x00000000);
  150. }
  151.  
  152.  
  153. sub decode_prefix {
  154.     return $_[0]->PP_decode_json($_[1], 0x00000001);
  155. }
  156.  
  157.  
  158. # accessor
  159.  
  160.  
  161. # pretty printing
  162.  
  163. sub pretty {
  164.     my ($self, $v) = @_;
  165.     my $enable = defined $v ? $v : 1;
  166.  
  167.     if ($enable) { # indent_length(3) for JSON::XS compatibility
  168.         $self->indent(1)->indent_length(3)->space_before(1)->space_after(1);
  169.     }
  170.     else {
  171.         $self->indent(0)->space_before(0)->space_after(0);
  172.     }
  173.  
  174.     $self;
  175. }
  176.  
  177. # etc
  178.  
  179. sub max_depth {
  180.     my $max  = defined $_[1] ? $_[1] : 0x80000000;
  181.     $_[0]->{max_depth} = $max;
  182.     $_[0];
  183. }
  184.  
  185.  
  186. sub get_max_depth { $_[0]->{max_depth}; }
  187.  
  188.  
  189. sub max_size {
  190.     my $max  = defined $_[1] ? $_[1] : 0;
  191.     $_[0]->{max_size} = $max;
  192.     $_[0];
  193. }
  194.  
  195.  
  196. sub get_max_size { $_[0]->{max_size}; }
  197.  
  198.  
  199. sub filter_json_object {
  200.     $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0;
  201.     $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
  202.     $_[0];
  203. }
  204.  
  205. sub filter_json_single_key_object {
  206.     if (@_ > 1) {
  207.         $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
  208.     }
  209.     $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
  210.     $_[0];
  211. }
  212.  
  213. sub indent_length {
  214.     if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
  215.         Carp::carp "The acceptable range of indent_length() is 0 to 15.";
  216.     }
  217.     else {
  218.         $_[0]->{indent_length} = $_[1];
  219.     }
  220.     $_[0];
  221. }
  222.  
  223. sub get_indent_length {
  224.     $_[0]->{indent_length};
  225. }
  226.  
  227. sub sort_by {
  228.     $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
  229.     $_[0];
  230. }
  231.  
  232. sub allow_bigint {
  233.     Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted.");
  234. }
  235.  
  236. ###############################
  237.  
  238. ###
  239. ### Perl => JSON
  240. ###
  241.  
  242.  
  243. { # Convert
  244.  
  245.     my $max_depth;
  246.     my $indent;
  247.     my $ascii;
  248.     my $latin1;
  249.     my $utf8;
  250.     my $space_before;
  251.     my $space_after;
  252.     my $canonical;
  253.     my $allow_blessed;
  254.     my $convert_blessed;
  255.  
  256.     my $indent_length;
  257.     my $escape_slash;
  258.     my $bignum;
  259.     my $as_nonblessed;
  260.  
  261.     my $depth;
  262.     my $indent_count;
  263.     my $keysort;
  264.  
  265.  
  266.     sub PP_encode_json {
  267.         my $self = shift;
  268.         my $obj  = shift;
  269.  
  270.         $indent_count = 0;
  271.         $depth        = 0;
  272.  
  273.         my $idx = $self->{PROPS};
  274.  
  275.         ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
  276.             $convert_blessed, $escape_slash, $bignum, $as_nonblessed)
  277.          = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
  278.                     P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED];
  279.  
  280.         ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
  281.  
  282.         $keysort = $canonical ? sub { $a cmp $b } : undef;
  283.  
  284.         if ($self->{sort_by}) {
  285.             $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
  286.                      : $self->{sort_by} =~ /\D+/       ? $self->{sort_by}
  287.                      : sub { $a cmp $b };
  288.         }
  289.  
  290.         encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
  291.              if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]);
  292.  
  293.         my $str  = $self->object_to_json($obj);
  294.  
  295.         $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
  296.  
  297.         unless ($ascii or $latin1 or $utf8) {
  298.             utf8::upgrade($str);
  299.         }
  300.  
  301.         if ($idx->[ P_SHRINK ]) {
  302.             utf8::downgrade($str, 1);
  303.         }
  304.  
  305.         return $str;
  306.     }
  307.  
  308.  
  309.     sub object_to_json {
  310.         my ($self, $obj) = @_;
  311.         my $type = ref($obj);
  312.  
  313.         if($type eq 'HASH'){
  314.             return $self->hash_to_json($obj);
  315.         }
  316.         elsif($type eq 'ARRAY'){
  317.             return $self->array_to_json($obj);
  318.         }
  319.         elsif ($type) { # blessed object?
  320.             if (blessed($obj)) {
  321.  
  322.                 return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
  323.  
  324.                 if ( $convert_blessed and $obj->can('TO_JSON') ) {
  325.                     my $result = $obj->TO_JSON();
  326.                     if ( defined $result and overload::Overloaded( $obj ) ) {
  327.                         if ( overload::StrVal( $obj ) eq $result ) {
  328.                             encode_error( sprintf(
  329.                                 "%s::TO_JSON method returned same object as was passed instead of a new one",
  330.                                 ref $obj
  331.                             ) );
  332.                         }
  333.                     }
  334.  
  335.                     return $self->object_to_json( $result );
  336.                 }
  337.  
  338.                 return "$obj" if ( $bignum and _is_bignum($obj) );
  339.                 return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed.
  340.  
  341.                 encode_error( sprintf("encountered object '%s', but neither allow_blessed "
  342.                     . "nor convert_blessed settings are enabled", $obj)
  343.                 ) unless ($allow_blessed);
  344.  
  345.                 return 'null';
  346.             }
  347.             else {
  348.                 return $self->value_to_json($obj);
  349.             }
  350.         }
  351.         else{
  352.             return $self->value_to_json($obj);
  353.         }
  354.     }
  355.  
  356.  
  357.     sub hash_to_json {
  358.         my ($self, $obj) = @_;
  359.         my ($k,$v);
  360.         my %res;
  361.  
  362.         encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
  363.                                          if (++$depth > $max_depth);
  364.  
  365.         my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
  366.         my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : '');
  367.  
  368.         if ( my $tie_class = tied %$obj ) {
  369.             if ( $tie_class->can('TIEHASH') ) {
  370.                 $tie_class =~ s/=.+$//;
  371.                 tie %res, $tie_class;
  372.             }
  373.         }
  374.  
  375.         # In the old Perl verions, tied hashes in bool context didn't work.
  376.         # So, we can't use such a way (%res ? a : b)
  377.         my $has;
  378.  
  379.         for my $k (keys %$obj) {
  380.             my $v = $obj->{$k};
  381.             $res{$k} = $self->object_to_json($v) || $self->value_to_json($v);
  382.             $has = 1 unless ( $has );
  383.         }
  384.  
  385.         --$depth;
  386.         $self->_down_indent() if ($indent);
  387.  
  388.         return '{' . ( $has ? $pre : '' )                                                   # indent
  389.                    . ( $has ? join(",$pre", map { utf8::decode($_) if ($] < 5.008);         # key for Perl 5.6
  390.                                                 string_to_json($self, $_) . $del . $res{$_} # key : value
  391.                                             } _sort( $self, \%res )
  392.                              ) . $post                                                      # indent
  393.                            : ''
  394.                      )
  395.              . '}';
  396.     }
  397.  
  398.  
  399.     sub array_to_json {
  400.         my ($self, $obj) = @_;
  401.         my @res;
  402.  
  403.         encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
  404.                                          if (++$depth > $max_depth);
  405.  
  406.         my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
  407.  
  408.         if (my $tie_class = tied @$obj) {
  409.             if ( $tie_class->can('TIEARRAY') ) {
  410.                 $tie_class =~ s/=.+$//;
  411.                 tie @res, $tie_class;
  412.             }
  413.         }
  414.  
  415.         for my $v (@$obj){
  416.             push @res, $self->object_to_json($v) || $self->value_to_json($v);
  417.         }
  418.  
  419.         --$depth;
  420.         $self->_down_indent() if ($indent);
  421.  
  422.         return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']';
  423.     }
  424.  
  425.  
  426.     sub value_to_json {
  427.         my ($self, $value) = @_;
  428.  
  429.         return 'null' if(!defined $value);
  430.  
  431.         my $b_obj = B::svref_2object(\$value);  # for round trip problem
  432.         my $flags = $b_obj->FLAGS;
  433.  
  434.         return $value # as is 
  435.             if ( (    $flags & B::SVf_IOK or $flags & B::SVp_IOK
  436.                    or $flags & B::SVf_NOK or $flags & B::SVp_NOK
  437.                  ) and !($flags & B::SVf_POK )
  438.             ); # SvTYPE is IV or NV?
  439.  
  440.         my $type = ref($value);
  441.  
  442.         if(!$type){
  443.             return string_to_json($self, $value);
  444.         }
  445.         elsif( blessed($value) and  $value->isa('JSON::PP::Boolean') ){
  446.             return $$value == 1 ? 'true' : 'false';
  447.         }
  448.         elsif ($type) {
  449.             if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
  450.                 return $self->value_to_json("$value");
  451.             }
  452.  
  453.             if ($type eq 'SCALAR' and defined $$value) {
  454.                 return   $$value eq '1' ? 'true'
  455.                        : $$value eq '0' ? 'false'
  456.                        : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
  457.                        : encode_error("cannot encode reference to scalar");
  458.             }
  459.  
  460.              if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
  461.                  return 'null';
  462.              }
  463.              else {
  464.                  if ( $type eq 'SCALAR' or $type eq 'REF' ) {
  465.                     encode_error("cannot encode reference to scalar");
  466.                  }
  467.                  else {
  468.                     encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
  469.                  }
  470.              }
  471.  
  472.         }
  473.         else {
  474.             return $self->{fallback}->($value)
  475.                  if ($self->{fallback} and ref($self->{fallback}) eq 'CODE');
  476.             return 'null';
  477.         }
  478.  
  479.     }
  480.  
  481.  
  482.     my %esc = (
  483.         "\n" => '\n',
  484.         "\r" => '\r',
  485.         "\t" => '\t',
  486.         "\f" => '\f',
  487.         "\b" => '\b',
  488.         "\"" => '\"',
  489.         "\\" => '\\\\',
  490.         "\'" => '\\\'',
  491.     );
  492.  
  493.  
  494.     sub string_to_json {
  495.         my ($self, $arg) = @_;
  496.  
  497.         $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
  498.         $arg =~ s/\//\\\//g if ($escape_slash);
  499.         $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
  500.  
  501.         if ($ascii) {
  502.             $arg = JSON_PP_encode_ascii($arg);
  503.         }
  504.  
  505.         if ($latin1) {
  506.             $arg = JSON_PP_encode_latin1($arg);
  507.         }
  508.  
  509.         if ($utf8) {
  510.             utf8::encode($arg);
  511.         }
  512.  
  513.         return '"' . $arg . '"';
  514.     }
  515.  
  516.  
  517.     sub blessed_to_json {
  518.         my $b_obj = B::svref_2object($_[1]);
  519.         if ($b_obj->isa('B::HV')) {
  520.             return $_[0]->hash_to_json($_[1]);
  521.         }
  522.         elsif ($b_obj->isa('B::AV')) {
  523.             return $_[0]->array_to_json($_[1]);
  524.         }
  525.         else {
  526.             return 'null';
  527.         }
  528.     }
  529.  
  530.  
  531.     sub encode_error {
  532.         my $error  = shift;
  533.         Carp::croak "$error";
  534.     }
  535.  
  536.  
  537.     sub _sort {
  538.         my ($self, $res) = @_;
  539.         defined $keysort ? (sort $keysort (keys %$res)) : keys %$res;
  540.     }
  541.  
  542.  
  543.     sub _up_indent {
  544.         my $self  = shift;
  545.         my $space = ' ' x $indent_length;
  546.  
  547.         my ($pre,$post) = ('','');
  548.  
  549.         $post = "\n" . $space x $indent_count;
  550.  
  551.         $indent_count++;
  552.  
  553.         $pre = "\n" . $space x $indent_count;
  554.  
  555.         return ($pre,$post);
  556.     }
  557.  
  558.  
  559.     sub _down_indent { $indent_count--; }
  560.  
  561.  
  562.     sub PP_encode_box {
  563.         {
  564.             depth        => $depth,
  565.             indent_count => $indent_count,
  566.         };
  567.     }
  568.  
  569. } # Convert
  570.  
  571.  
  572. sub _encode_ascii {
  573.     join('',
  574.         map {
  575.             $_ <= 127 ?
  576.                 chr($_) :
  577.             $_ <= 65535 ?
  578.                 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
  579.         } unpack('U*', $_[0])
  580.     );
  581. }
  582.  
  583.  
  584. sub _encode_latin1 {
  585.     join('',
  586.         map {
  587.             $_ <= 255 ?
  588.                 chr($_) :
  589.             $_ <= 65535 ?
  590.                 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
  591.         } unpack('U*', $_[0])
  592.     );
  593. }
  594.  
  595.  
  596. sub _encode_surrogates { # from perlunicode
  597.     my $uni = $_[0] - 0x10000;
  598.     return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
  599. }
  600.  
  601.  
  602. sub _is_bignum {
  603.     $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
  604. }
  605.  
  606.  
  607.  
  608. #
  609. # JSON => Perl
  610. #
  611.  
  612. my $max_intsize;
  613.  
  614. BEGIN {
  615.     my $checkint = 1111;
  616.     for my $d (5..30) {
  617.         $checkint .= 1;
  618.         my $int   = eval qq| $checkint |;
  619.         if ($int =~ /[eE]/) {
  620.             $max_intsize = $d - 1;
  621.             last;
  622.         }
  623.     }
  624. }
  625.  
  626. { # PARSE 
  627.  
  628.     my %escapes = ( #  by Jeremy Muhlich <jmuhlich [at] bitflood.org>
  629.         b    => "\x8",
  630.         t    => "\x9",
  631.         n    => "\xA",
  632.         f    => "\xC",
  633.         r    => "\xD",
  634.         '\\' => '\\',
  635.         '"'  => '"',
  636.         '/'  => '/',
  637.     );
  638.  
  639.     my $text; # json data
  640.     my $at;   # offset
  641.     my $ch;   # 1chracter
  642.     my $len;  # text length (changed according to UTF8 or NON UTF8)
  643.     # INTERNAL
  644.     my $depth;          # nest counter
  645.     my $encoding;       # json text encoding
  646.     my $is_valid_utf8;  # temp variable
  647.     my $utf8_len;       # utf8 byte length
  648.     # FLAGS
  649.     my $utf8;           # must be utf8
  650.     my $max_depth;      # max nest nubmer of objects and arrays
  651.     my $max_size;
  652.     my $relaxed;
  653.     my $cb_object;
  654.     my $cb_sk_object;
  655.  
  656.     my $F_HOOK;
  657.  
  658.     my $allow_bigint;   # using Math::BigInt
  659.     my $singlequote;    # loosely quoting
  660.     my $loose;          # 
  661.     my $allow_barekey;  # bareKey
  662.  
  663.     # $opt flag
  664.     # 0x00000001 .... decode_prefix
  665.     # 0x10000000 .... incr_parse
  666.  
  667.     sub PP_decode_json {
  668.         my ($self, $opt); # $opt is an effective flag during this decode_json.
  669.  
  670.         ($self, $text, $opt) = @_;
  671.  
  672.         ($at, $ch, $depth) = (0, '', 0);
  673.  
  674.         if ( !defined $text or ref $text ) {
  675.             decode_error("malformed JSON string, neither array, object, number, string or atom");
  676.         }
  677.  
  678.         my $idx = $self->{PROPS};
  679.  
  680.         ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote)
  681.             = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE];
  682.  
  683.         if ( $utf8 ) {
  684.             utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
  685.         }
  686.         else {
  687.             utf8::upgrade( $text );
  688.         }
  689.  
  690.         $len = length $text;
  691.  
  692.         ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
  693.              = @{$self}{qw/max_depth  max_size cb_object cb_sk_object F_HOOK/};
  694.  
  695.         if ($max_size > 1) {
  696.             use bytes;
  697.             my $bytes = length $text;
  698.             decode_error(
  699.                 sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
  700.                     , $bytes, $max_size), 1
  701.             ) if ($bytes > $max_size);
  702.         }
  703.  
  704.         # Currently no effect
  705.         # should use regexp
  706.         my @octets = unpack('C4', $text);
  707.         $encoding =   ( $octets[0] and  $octets[1]) ? 'UTF-8'
  708.                     : (!$octets[0] and  $octets[1]) ? 'UTF-16BE'
  709.                     : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
  710.                     : ( $octets[2]                ) ? 'UTF-16LE'
  711.                     : (!$octets[2]                ) ? 'UTF-32LE'
  712.                     : 'unknown';
  713.  
  714.         white(); # remove head white space
  715.  
  716.         my $valid_start = defined $ch; # Is there a first character for JSON structure?
  717.  
  718.         my $result = value();
  719.  
  720.         return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse
  721.  
  722.         decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start;
  723.  
  724.         if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) {
  725.                 decode_error(
  726.                 'JSON text must be an object or array (but found number, string, true, false or null,'
  727.                        . ' use allow_nonref to allow this)', 1);
  728.         }
  729.  
  730.         Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
  731.  
  732.         my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
  733.  
  734.         white(); # remove tail white space
  735.  
  736.         if ( $ch ) {
  737.             return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix
  738.             decode_error("garbage after JSON object");
  739.         }
  740.  
  741.         ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result;
  742.     }
  743.  
  744.  
  745.     sub next_chr {
  746.         return $ch = undef if($at >= $len);
  747.         $ch = substr($text, $at++, 1);
  748.     }
  749.  
  750.  
  751.     sub value {
  752.         white();
  753.         return          if(!defined $ch);
  754.         return object() if($ch eq '{');
  755.         return array()  if($ch eq '[');
  756.         return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
  757.         return number() if($ch =~ /[0-9]/ or $ch eq '-');
  758.         return word();
  759.     }
  760.  
  761.     sub string {
  762.         my ($i, $s, $t, $u);
  763.         my $utf16;
  764.         my $is_utf8;
  765.  
  766.         ($is_valid_utf8, $utf8_len) = ('', 0);
  767.  
  768.         $s = ''; # basically UTF8 flag on
  769.  
  770.         if($ch eq '"' or ($singlequote and $ch eq "'")){
  771.             my $boundChar = $ch if ($singlequote);
  772.  
  773.             OUTER: while( defined(next_chr()) ){
  774.  
  775.                 if((!$singlequote and $ch eq '"') or ($singlequote and $ch eq $boundChar)){
  776.                     next_chr();
  777.  
  778.                     if ($utf16) {
  779.                         decode_error("missing low surrogate character in surrogate pair");
  780.                     }
  781.  
  782.                     utf8::decode($s) if($is_utf8);
  783.  
  784.                     return $s;
  785.                 }
  786.                 elsif($ch eq '\\'){
  787.                     next_chr();
  788.                     if(exists $escapes{$ch}){
  789.                         $s .= $escapes{$ch};
  790.                     }
  791.                     elsif($ch eq 'u'){ # UNICODE handling
  792.                         my $u = '';
  793.  
  794.                         for(1..4){
  795.                             $ch = next_chr();
  796.                             last OUTER if($ch !~ /[0-9a-fA-F]/);
  797.                             $u .= $ch;
  798.                         }
  799.  
  800.                         # U+D800 - U+DBFF
  801.                         if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
  802.                             $utf16 = $u;
  803.                         }
  804.                         # U+DC00 - U+DFFF
  805.                         elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
  806.                             unless (defined $utf16) {
  807.                                 decode_error("missing high surrogate character in surrogate pair");
  808.                             }
  809.                             $is_utf8 = 1;
  810.                             $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
  811.                             $utf16 = undef;
  812.                         }
  813.                         else {
  814.                             if (defined $utf16) {
  815.                                 decode_error("surrogate pair expected");
  816.                             }
  817.  
  818.                             if ( ( my $hex = hex( $u ) ) > 127 ) {
  819.                                 $is_utf8 = 1;
  820.                                 $s .= JSON_PP_decode_unicode($u) || next;
  821.                             }
  822.                             else {
  823.                                 $s .= chr $hex;
  824.                             }
  825.                         }
  826.  
  827.                     }
  828.                     else{
  829.                         unless ($loose) {
  830.                             $at -= 2;
  831.                             decode_error('illegal backslash escape sequence in string');
  832.                         }
  833.                         $s .= $ch;
  834.                     }
  835.                 }
  836.                 else{
  837.  
  838.                     if ( ord $ch  > 127 ) {
  839.                         if ( $utf8 ) {
  840.                             unless( $ch = is_valid_utf8($ch) ) {
  841.                                 $at -= 1;
  842.                                 decode_error("malformed UTF-8 character in JSON string");
  843.                             }
  844.                             else {
  845.                                 $at += $utf8_len - 1;
  846.                             }
  847.                         }
  848.                         else {
  849.                             utf8::encode( $ch );
  850.                         }
  851.  
  852.                         $is_utf8 = 1;
  853.                     }
  854.  
  855.                     if (!$loose) {
  856.                         if ($ch =~ /[\x00-\x1f\x22\x5c]/)  { # '/' ok
  857.                             $at--;
  858.                             decode_error('invalid character encountered while parsing JSON string');
  859.                         }
  860.                     }
  861.  
  862.                     $s .= $ch;
  863.                 }
  864.             }
  865.         }
  866.  
  867.         decode_error("unexpected end of string while parsing JSON string");
  868.     }
  869.  
  870.  
  871.     sub white {
  872.         while( defined $ch  ){
  873.             if($ch le ' '){
  874.                 next_chr();
  875.             }
  876.             elsif($ch eq '/'){
  877.                 next_chr();
  878.                 if(defined $ch and $ch eq '/'){
  879.                     1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
  880.                 }
  881.                 elsif(defined $ch and $ch eq '*'){
  882.                     next_chr();
  883.                     while(1){
  884.                         if(defined $ch){
  885.                             if($ch eq '*'){
  886.                                 if(defined(next_chr()) and $ch eq '/'){
  887.                                     next_chr();
  888.                                     last;
  889.                                 }
  890.                             }
  891.                             else{
  892.                                 next_chr();
  893.                             }
  894.                         }
  895.                         else{
  896.                             decode_error("Unterminated comment");
  897.                         }
  898.                     }
  899.                     next;
  900.                 }
  901.                 else{
  902.                     $at--;
  903.                     decode_error("malformed JSON string, neither array, object, number, string or atom");
  904.                 }
  905.             }
  906.             else{
  907.                 if ($relaxed and $ch eq '#') { # correctly?
  908.                     pos($text) = $at;
  909.                     $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
  910.                     $at = pos($text);
  911.                     next_chr;
  912.                     next;
  913.                 }
  914.  
  915.                 last;
  916.             }
  917.         }
  918.     }
  919.  
  920.  
  921.     sub array {
  922.         my $a  = [];
  923.  
  924.         decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
  925.                                                     if (++$depth > $max_depth);
  926.  
  927.         next_chr();
  928.         white();
  929.  
  930.         if(defined $ch and $ch eq ']'){
  931.             --$depth;
  932.             next_chr();
  933.             return $a;
  934.         }
  935.         else {
  936.             while(defined($ch)){
  937.                 push @$a, value();
  938.  
  939.                 white();
  940.  
  941.                 if (!defined $ch) {
  942.                     last;
  943.                 }
  944.  
  945.                 if($ch eq ']'){
  946.                     --$depth;
  947.                     next_chr();
  948.                     return $a;
  949.                 }
  950.  
  951.                 if($ch ne ','){
  952.                     last;
  953.                 }
  954.  
  955.                 next_chr();
  956.                 white();
  957.  
  958.                 if ($relaxed and $ch eq ']') {
  959.                     --$depth;
  960.                     next_chr();
  961.                     return $a;
  962.                 }
  963.  
  964.             }
  965.         }
  966.  
  967.         decode_error(", or ] expected while parsing array");
  968.     }
  969.  
  970.  
  971.     sub object {
  972.         my $o = {};
  973.         my $k;
  974.  
  975.         decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
  976.                                                 if (++$depth > $max_depth);
  977.         next_chr();
  978.         white();
  979.  
  980.         if(defined $ch and $ch eq '}'){
  981.             --$depth;
  982.             next_chr();
  983.             if ($F_HOOK) {
  984.                 return _json_object_hook($o);
  985.             }
  986.             return $o;
  987.         }
  988.         else {
  989.             while (defined $ch) {
  990.                 $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
  991.                 white();
  992.  
  993.                 if(!defined $ch or $ch ne ':'){
  994.                     $at--;
  995.                     decode_error("':' expected");
  996.                 }
  997.  
  998.                 next_chr();
  999.                 $o->{$k} = value();
  1000.                 white();
  1001.  
  1002.                 last if (!defined $ch);
  1003.  
  1004.                 if($ch eq '}'){
  1005.                     --$depth;
  1006.                     next_chr();
  1007.                     if ($F_HOOK) {
  1008.                         return _json_object_hook($o);
  1009.                     }
  1010.                     return $o;
  1011.                 }
  1012.  
  1013.                 if($ch ne ','){
  1014.                     last;
  1015.                 }
  1016.  
  1017.                 next_chr();
  1018.                 white();
  1019.  
  1020.                 if ($relaxed and $ch eq '}') {
  1021.                     --$depth;
  1022.                     next_chr();
  1023.                     if ($F_HOOK) {
  1024.                         return _json_object_hook($o);
  1025.                     }
  1026.                     return $o;
  1027.                 }
  1028.  
  1029.             }
  1030.  
  1031.         }
  1032.  
  1033.         $at--;
  1034.         decode_error(", or } expected while parsing object/hash");
  1035.     }
  1036.  
  1037.  
  1038.     sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
  1039.         my $key;
  1040.         while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){
  1041.             $key .= $ch;
  1042.             next_chr();
  1043.         }
  1044.         return $key;
  1045.     }
  1046.  
  1047.  
  1048.     sub word {
  1049.         my $word =  substr($text,$at-1,4);
  1050.  
  1051.         if($word eq 'true'){
  1052.             $at += 3;
  1053.             next_chr;
  1054.             return $JSON::PP::true;
  1055.         }
  1056.         elsif($word eq 'null'){
  1057.             $at += 3;
  1058.             next_chr;
  1059.             return undef;
  1060.         }
  1061.         elsif($word eq 'fals'){
  1062.             $at += 3;
  1063.             if(substr($text,$at,1) eq 'e'){
  1064.                 $at++;
  1065.                 next_chr;
  1066.                 return $JSON::PP::false;
  1067.             }
  1068.         }
  1069.  
  1070.         $at--; # for decode_error report
  1071.  
  1072.         decode_error("'null' expected")  if ($word =~ /^n/);
  1073.         decode_error("'true' expected")  if ($word =~ /^t/);
  1074.         decode_error("'false' expected") if ($word =~ /^f/);
  1075.         decode_error("malformed JSON string, neither array, object, number, string or atom");
  1076.     }
  1077.  
  1078.  
  1079.     sub number {
  1080.         my $n    = '';
  1081.         my $v;
  1082.  
  1083.         # According to RFC4627, hex or oct digts are invalid.
  1084.         if($ch eq '0'){
  1085.             my $peek = substr($text,$at,1);
  1086.             my $hex  = $peek =~ /[xX]/; # 0 or 1
  1087.  
  1088.             if($hex){
  1089.                 decode_error("malformed number (leading zero must not be followed by another digit)");
  1090.                 ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/);
  1091.             }
  1092.             else{ # oct
  1093.                 ($n) = ( substr($text, $at) =~ /^([0-7]+)/);
  1094.                 if (defined $n and length $n > 1) {
  1095.                     decode_error("malformed number (leading zero must not be followed by another digit)");
  1096.                 }
  1097.             }
  1098.  
  1099.             if(defined $n and length($n)){
  1100.                 if (!$hex and length($n) == 1) {
  1101.                    decode_error("malformed number (leading zero must not be followed by another digit)");
  1102.                 }
  1103.                 $at += length($n) + $hex;
  1104.                 next_chr;
  1105.                 return $hex ? hex($n) : oct($n);
  1106.             }
  1107.         }
  1108.  
  1109.         if($ch eq '-'){
  1110.             $n = '-';
  1111.             next_chr;
  1112.             if (!defined $ch or $ch !~ /\d/) {
  1113.                 decode_error("malformed number (no digits after initial minus)");
  1114.             }
  1115.         }
  1116.  
  1117.         while(defined $ch and $ch =~ /\d/){
  1118.             $n .= $ch;
  1119.             next_chr;
  1120.         }
  1121.  
  1122.         if(defined $ch and $ch eq '.'){
  1123.             $n .= '.';
  1124.  
  1125.             next_chr;
  1126.             if (!defined $ch or $ch !~ /\d/) {
  1127.                 decode_error("malformed number (no digits after decimal point)");
  1128.             }
  1129.             else {
  1130.                 $n .= $ch;
  1131.             }
  1132.  
  1133.             while(defined(next_chr) and $ch =~ /\d/){
  1134.                 $n .= $ch;
  1135.             }
  1136.         }
  1137.  
  1138.         if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
  1139.             $n .= $ch;
  1140.             next_chr;
  1141.  
  1142.             if(defined($ch) and ($ch eq '+' or $ch eq '-')){
  1143.                 $n .= $ch;
  1144.                 next_chr;
  1145.                 if (!defined $ch or $ch =~ /\D/) {
  1146.                     decode_error("malformed number (no digits after exp sign)");
  1147.                 }
  1148.                 $n .= $ch;
  1149.             }
  1150.             elsif(defined($ch) and $ch =~ /\d/){
  1151.                 $n .= $ch;
  1152.             }
  1153.             else {
  1154.                 decode_error("malformed number (no digits after exp sign)");
  1155.             }
  1156.  
  1157.             while(defined(next_chr) and $ch =~ /\d/){
  1158.                 $n .= $ch;
  1159.             }
  1160.  
  1161.         }
  1162.  
  1163.         $v .= $n;
  1164.  
  1165.         if ($v !~ /[.eE]/ and length $v > $max_intsize) {
  1166.             if ($allow_bigint) { # from Adam Sussman
  1167.                 require Math::BigInt;
  1168.                 return Math::BigInt->new($v);
  1169.             }
  1170.             else {
  1171.                 return "$v";
  1172.             }
  1173.         }
  1174.         elsif ($allow_bigint) {
  1175.             require Math::BigFloat;
  1176.             return Math::BigFloat->new($v);
  1177.         }
  1178.  
  1179.         return 0+$v;
  1180.     }
  1181.  
  1182.  
  1183.     sub is_valid_utf8 {
  1184.  
  1185.         $utf8_len = $_[0] =~ /[\x00-\x7F]/  ? 1
  1186.                   : $_[0] =~ /[\xC2-\xDF]/  ? 2
  1187.                   : $_[0] =~ /[\xE0-\xEF]/  ? 3
  1188.                   : $_[0] =~ /[\xF0-\xF4]/  ? 4
  1189.                   : 0
  1190.                   ;
  1191.  
  1192.         return unless $utf8_len;
  1193.  
  1194.         my $is_valid_utf8 = substr($text, $at - 1, $utf8_len);
  1195.  
  1196.         return ( $is_valid_utf8 =~ /^(?:
  1197.              [\x00-\x7F]
  1198.             |[\xC2-\xDF][\x80-\xBF]
  1199.             |[\xE0][\xA0-\xBF][\x80-\xBF]
  1200.             |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
  1201.             |[\xED][\x80-\x9F][\x80-\xBF]
  1202.             |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
  1203.             |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
  1204.             |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
  1205.             |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
  1206.         )$/x )  ? $is_valid_utf8 : '';
  1207.     }
  1208.  
  1209.  
  1210.     sub decode_error {
  1211.         my $error  = shift;
  1212.         my $no_rep = shift;
  1213.         my $str    = defined $text ? substr($text, $at) : '';
  1214.         my $mess   = '';
  1215.         my $type   = $] >= 5.008           ? 'U*'
  1216.                    : $] <  5.006           ? 'C*'
  1217.                    : utf8::is_utf8( $str ) ? 'U*' # 5.6
  1218.                    : 'C*'
  1219.                    ;
  1220.  
  1221.         for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
  1222.             $mess .=  $c == 0x07 ? '\a'
  1223.                     : $c == 0x09 ? '\t'
  1224.                     : $c == 0x0a ? '\n'
  1225.                     : $c == 0x0d ? '\r'
  1226.                     : $c == 0x0c ? '\f'
  1227.                     : $c <  0x20 ? sprintf('\x{%x}', $c)
  1228.                     : $c == 0x5c ? '\\\\'
  1229.                     : $c <  0x80 ? chr($c)
  1230.                     : sprintf('\x{%x}', $c)
  1231.                     ;
  1232.             if ( length $mess >= 20 ) {
  1233.                 $mess .= '...';
  1234.                 last;
  1235.             }
  1236.         }
  1237.  
  1238.         unless ( length $mess ) {
  1239.             $mess = '(end of string)';
  1240.         }
  1241.  
  1242.         Carp::croak (
  1243.             $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
  1244.         );
  1245.  
  1246.     }
  1247.  
  1248.  
  1249.     sub _json_object_hook {
  1250.         my $o    = $_[0];
  1251.         my @ks = keys %{$o};
  1252.  
  1253.         if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
  1254.             my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
  1255.             if (@val == 1) {
  1256.                 return $val[0];
  1257.             }
  1258.         }
  1259.  
  1260.         my @val = $cb_object->($o) if ($cb_object);
  1261.         if (@val == 0 or @val > 1) {
  1262.             return $o;
  1263.         }
  1264.         else {
  1265.             return $val[0];
  1266.         }
  1267.     }
  1268.  
  1269.  
  1270.     sub PP_decode_box {
  1271.         {
  1272.             text    => $text,
  1273.             at      => $at,
  1274.             ch      => $ch,
  1275.             len     => $len,
  1276.             depth   => $depth,
  1277.             encoding      => $encoding,
  1278.             is_valid_utf8 => $is_valid_utf8,
  1279.         };
  1280.     }
  1281.  
  1282. } # PARSE
  1283.  
  1284.  
  1285. sub _decode_surrogates { # from perlunicode
  1286.     my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
  1287.     my $un  = pack('U*', $uni);
  1288.     utf8::encode( $un );
  1289.     return $un;
  1290. }
  1291.  
  1292.  
  1293. sub _decode_unicode {
  1294.     my $un = pack('U', hex shift);
  1295.     utf8::encode( $un );
  1296.     return $un;
  1297. }
  1298.  
  1299.  
  1300.  
  1301.  
  1302.  
  1303. ###############################
  1304. # Utilities
  1305. #
  1306.  
  1307. BEGIN {
  1308.     eval 'require Scalar::Util';
  1309.     unless($@){
  1310.         *JSON::PP::blessed = \&Scalar::Util::blessed;
  1311.     }
  1312.     else{ # This code is from Sclar::Util.
  1313.         # warn $@;
  1314.         eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
  1315.         *JSON::PP::blessed = sub {
  1316.             local($@, $SIG{__DIE__}, $SIG{__WARN__});
  1317.             ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
  1318.         };
  1319.     }
  1320. }
  1321.  
  1322.  
  1323. # shamely copied and modified from JSON::XS code.
  1324.  
  1325. $JSON::PP::true  = do { bless \(my $dummy = 1), "JSON::PP::Boolean" };
  1326. $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" };
  1327.  
  1328. sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); }
  1329.  
  1330. sub true  { $JSON::PP::true  }
  1331. sub false { $JSON::PP::false }
  1332. sub null  { undef; }
  1333.  
  1334. ###############################
  1335.  
  1336. package JSON::PP::Boolean;
  1337.  
  1338.  
  1339. use overload (
  1340.    "0+"     => sub { ${$_[0]} },
  1341.    "++"     => sub { $_[0] = ${$_[0]} + 1 },
  1342.    "--"     => sub { $_[0] = ${$_[0]} - 1 },
  1343.    fallback => 1,
  1344. );
  1345.  
  1346.  
  1347. ###############################
  1348.  
  1349. package JSON::PP::IncrParser;
  1350.  
  1351. use strict;
  1352.  
  1353. use constant INCR_M_WS   => 0; # initial whitespace skipping
  1354. use constant INCR_M_STR  => 1; # inside string
  1355. use constant INCR_M_BS   => 2; # inside backslash
  1356. use constant INCR_M_JSON => 3; # outside anything, count nesting
  1357. use constant INCR_M_C0   => 4;
  1358. use constant INCR_M_C1   => 5;
  1359.  
  1360. $JSON::PP::IncrParser::VERSION = '1.01';
  1361.  
  1362. my $unpack_format = $] < 5.006 ? 'C*' : 'U*';
  1363.  
  1364. sub new {
  1365.     my ( $class ) = @_;
  1366.  
  1367.     bless {
  1368.         incr_nest    => 0,
  1369.         incr_text    => undef,
  1370.         incr_parsing => 0,
  1371.         incr_p       => 0,
  1372.     }, $class;
  1373. }
  1374.  
  1375.  
  1376. sub incr_parse {
  1377.     my ( $self, $coder, $text ) = @_;
  1378.  
  1379.     $self->{incr_text} = '' unless ( defined $self->{incr_text} );
  1380.  
  1381.     if ( defined $text ) {
  1382.         if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) {
  1383.             utf8::upgrade( $self->{incr_text} ) ;
  1384.             utf8::decode( $self->{incr_text} ) ;
  1385.         }
  1386.         $self->{incr_text} .= $text;
  1387.     }
  1388.  
  1389.  
  1390.     my $max_size = $coder->get_max_size;
  1391.  
  1392.     if ( defined wantarray ) {
  1393.  
  1394.         $self->{incr_mode} = INCR_M_WS;
  1395.  
  1396.         if ( wantarray ) {
  1397.             my @ret;
  1398.  
  1399.             $self->{incr_parsing} = 1;
  1400.  
  1401.             do {
  1402.                 push @ret, $self->_incr_parse( $coder, $self->{incr_text} );
  1403.  
  1404.                 unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) {
  1405.                     $self->{incr_mode} = INCR_M_WS;
  1406.                 }
  1407.  
  1408.             } until ( !$self->{incr_text} );
  1409.  
  1410.             $self->{incr_parsing} = 0;
  1411.  
  1412.             return @ret;
  1413.         }
  1414.         else { # in scalar context
  1415.             $self->{incr_parsing} = 1;
  1416.             my $obj = $self->_incr_parse( $coder, $self->{incr_text} );
  1417.             $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans
  1418.             return $obj ? $obj : undef; # $obj is an empty string, parsing was completed.
  1419.         }
  1420.  
  1421.     }
  1422.  
  1423. }
  1424.  
  1425.  
  1426. sub _incr_parse {
  1427.     my ( $self, $coder, $text, $skip ) = @_;
  1428.     my $p = $self->{incr_p};
  1429.     my $restore = $p;
  1430.  
  1431.     my @obj;
  1432.     my $len = length $text;
  1433.  
  1434.     if ( $self->{incr_mode} == INCR_M_WS ) {
  1435.         while ( $len > $p ) {
  1436.             my $s = substr( $text, $p, 1 );
  1437.             $p++ and next if ( 0x20 >= unpack($unpack_format, $s) );
  1438.             $self->{incr_mode} = INCR_M_JSON;
  1439.             last;
  1440.        }
  1441.     }
  1442.  
  1443.     while ( $len > $p ) {
  1444.         my $s = substr( $text, $p++, 1 );
  1445.  
  1446.         if ( $s eq '"' ) {
  1447.             if ( $self->{incr_mode} != INCR_M_STR  ) {
  1448.                 $self->{incr_mode} = INCR_M_STR;
  1449.             }
  1450.             else {
  1451.                 $self->{incr_mode} = INCR_M_JSON;
  1452.                 unless ( $self->{incr_nest} ) {
  1453.                     last;
  1454.                 }
  1455.             }
  1456.         }
  1457.  
  1458.         if ( $self->{incr_mode} == INCR_M_JSON ) {
  1459.  
  1460.             if ( $s eq '[' or $s eq '{' ) {
  1461.                 if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
  1462.                     Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
  1463.                 }
  1464.             }
  1465.             elsif ( $s eq ']' or $s eq '}' ) {
  1466.                 last if ( --$self->{incr_nest} <= 0 );
  1467.             }
  1468.             elsif ( $s eq '#' ) {
  1469.                 while ( $len > $p ) {
  1470.                     last if substr( $text, $p++, 1 ) eq "\n";
  1471.                 }
  1472.             }
  1473.  
  1474.         }
  1475.  
  1476.     }
  1477.  
  1478.     $self->{incr_p} = $p;
  1479.  
  1480.     return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 );
  1481.  
  1482.     return '' unless ( length substr( $self->{incr_text}, 0, $p ) );
  1483.  
  1484.     local $Carp::CarpLevel = 2;
  1485.  
  1486.     $self->{incr_p} = $restore;
  1487.     $self->{incr_c} = $p;
  1488.  
  1489.     my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 );
  1490.  
  1491.     $self->{incr_text} = substr( $self->{incr_text}, $p );
  1492.     $self->{incr_p} = 0;
  1493.  
  1494.     return $obj or '';
  1495. }
  1496.  
  1497.  
  1498. sub incr_text {
  1499.     if ( $_[0]->{incr_parsing} ) {
  1500.         Carp::croak("incr_text can not be called when the incremental parser already started parsing");
  1501.     }
  1502.     $_[0]->{incr_text};
  1503. }
  1504.  
  1505.  
  1506. sub incr_skip {
  1507.     my $self  = shift;
  1508.     $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} );
  1509.     $self->{incr_p} = 0;
  1510. }
  1511.  
  1512.  
  1513. sub incr_reset {
  1514.     my $self = shift;
  1515.     $self->{incr_text}    = undef;
  1516.     $self->{incr_p}       = 0;
  1517.     $self->{incr_mode}    = 0;
  1518.     $self->{incr_nest}    = 0;
  1519.     $self->{incr_parsing} = 0;
  1520. }
  1521.  
  1522. ###############################
  1523.  
  1524.  
  1525. 1;
  1526. __END__
  1527. =pod
  1528.  
  1529. =head1 NAME
  1530.  
  1531. JSON::PP - JSON::XS compatible pure-Perl module.
  1532.  
  1533. =head1 SYNOPSIS
  1534.  
  1535.  use JSON::PP;
  1536.  
  1537.  # exported functions, they croak on error
  1538.  # and expect/generate UTF-8
  1539.  
  1540.  $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
  1541.  $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
  1542.  
  1543.  # OO-interface
  1544.  
  1545.  $coder = JSON::PP->new->ascii->pretty->allow_nonref;
  1546.  $pretty_printed_unencoded = $coder->encode ($perl_scalar);
  1547.  $perl_scalar = $coder->decode ($unicode_json_text);
  1548.  
  1549.  # Note that JSON version 2.0 and above will automatically use
  1550.  # JSON::XS or JSON::PP, so you should be able to just:
  1551.  
  1552.  use JSON;
  1553.  
  1554. =head1 DESCRIPTION
  1555.  
  1556. This module is L<JSON::XS> compatible pure Perl module.
  1557. (Perl 5.8 or later is recommended)
  1558.  
  1559. JSON::XS is the fastest and most proper JSON module on CPAN.
  1560. It is written by Marc Lehmann in C, so must be compiled and
  1561. installed in the used environment.
  1562.  
  1563. JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
  1564.  
  1565.  
  1566. =head2 FEATURES
  1567.  
  1568. =over
  1569.  
  1570. =item * correct unicode handling
  1571.  
  1572. This module knows how to handle Unicode (depending on Perl version).
  1573.  
  1574. See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> and L<UNICODE HANDLING ON PERLS>.
  1575.  
  1576.  
  1577. =item * round-trip integrity
  1578.  
  1579. When you serialise a perl data structure using only data types supported
  1580. by JSON and Perl, the deserialised data structure is identical on the Perl
  1581. level. (e.g. the string "2.0" doesn't suddenly become "2" just because
  1582. it looks like a number). There I<are> minor exceptions to this, read the
  1583. MAPPING section below to learn about those.
  1584.  
  1585.  
  1586. =item * strict checking of JSON correctness
  1587.  
  1588. There is no guessing, no generating of illegal JSON texts by default,
  1589. and only JSON is accepted as input by default (the latter is a security feature).
  1590. But when some options are set, loose chcking features are available.
  1591.  
  1592. =back
  1593.  
  1594. =head1 FUNCTIONS
  1595.  
  1596. Basically, check to L<JSON> or L<JSON::XS>.
  1597.  
  1598. =head2 encode_json
  1599.  
  1600.     $json_text = encode_json $perl_scalar
  1601.  
  1602. =head2 decode_json
  1603.  
  1604.     $perl_scalar = decode_json $json_text
  1605.  
  1606. =head2 JSON::PP::true
  1607.  
  1608. Returns JSON true value which is blessed object.
  1609. It C<isa> JSON::PP::Boolean object.
  1610.  
  1611. =head2 JSON::PP::false
  1612.  
  1613. Returns JSON false value which is blessed object.
  1614. It C<isa> JSON::PP::Boolean object.
  1615.  
  1616. =head2 JSON::PP::null
  1617.  
  1618. Returns C<undef>.
  1619.  
  1620. =head1 METHODS
  1621.  
  1622. Basically, check to L<JSON> or L<JSON::XS>.
  1623.  
  1624. =head2 new
  1625.  
  1626.     $json = new JSON::PP
  1627.  
  1628. Rturns a new JSON::PP object that can be used to de/encode JSON
  1629. strings.
  1630.  
  1631. =head2 ascii
  1632.  
  1633.     $json = $json->ascii([$enable])
  1634.     
  1635.     $enabled = $json->get_ascii
  1636.  
  1637. If $enable is true (or missing), then the encode method will not generate characters outside
  1638. the code range 0..127. Any Unicode characters outside that range will be escaped using either
  1639. a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
  1640. (See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>).
  1641.  
  1642. In Perl 5.005, there is no character having high value (more than 255).
  1643. See to L<UNICODE HANDLING ON PERLS>.
  1644.  
  1645. If $enable is false, then the encode method will not escape Unicode characters unless
  1646. required by the JSON syntax or other flags. This results in a faster and more compact format.
  1647.  
  1648.   JSON::PP->new->ascii(1)->encode([chr 0x10401])
  1649.   => ["\ud801\udc01"]
  1650.  
  1651. =head2 latin1
  1652.  
  1653.     $json = $json->latin1([$enable])
  1654.     
  1655.     $enabled = $json->get_latin1
  1656.  
  1657. If $enable is true (or missing), then the encode method will encode the resulting JSON
  1658. text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
  1659.  
  1660. If $enable is false, then the encode method will not escape Unicode characters
  1661. unless required by the JSON syntax or other flags.
  1662.  
  1663.   JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
  1664.   => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
  1665.  
  1666. See to L<UNICODE HANDLING ON PERLS>.
  1667.  
  1668. =head2 utf8
  1669.  
  1670.     $json = $json->utf8([$enable])
  1671.     
  1672.     $enabled = $json->get_utf8
  1673.  
  1674. If $enable is true (or missing), then the encode method will encode the JSON result
  1675. into UTF-8, as required by many protocols, while the decode method expects to be handled
  1676. an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
  1677. characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
  1678.  
  1679. (In Perl 5.005, any character outside the range 0..255 does not exist.
  1680. See to L<UNICODE HANDLING ON PERLS>.)
  1681.  
  1682. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
  1683. encoding families, as described in RFC4627.
  1684.  
  1685. If $enable is false, then the encode method will return the JSON string as a (non-encoded)
  1686. Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
  1687. (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
  1688.  
  1689. Example, output UTF-16BE-encoded JSON:
  1690.  
  1691.   use Encode;
  1692.   $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
  1693.  
  1694. Example, decode UTF-32LE-encoded JSON:
  1695.  
  1696.   use Encode;
  1697.   $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
  1698.  
  1699.  
  1700. =head2 pretty
  1701.  
  1702.     $json = $json->pretty([$enable])
  1703.  
  1704. This enables (or disables) all of the C<indent>, C<space_before> and
  1705. C<space_after> flags in one call to generate the most readable
  1706. (or most compact) form possible.
  1707.  
  1708. =head2 indent
  1709.  
  1710.     $json = $json->indent([$enable])
  1711.     
  1712.     $enabled = $json->get_indent
  1713.  
  1714. The default indent space length is three.
  1715. You can use C<indent_length> to change the length.
  1716.  
  1717. =head2 space_before
  1718.  
  1719.     $json = $json->space_before([$enable])
  1720.     
  1721.     $enabled = $json->get_space_before
  1722.  
  1723. =head2 space_after
  1724.  
  1725.     $json = $json->space_after([$enable])
  1726.     
  1727.     $enabled = $json->get_space_after
  1728.  
  1729. =head2 relaxed
  1730.  
  1731.     $json = $json->relaxed([$enable])
  1732.     
  1733.     $enabled = $json->get_relaxed
  1734.  
  1735. =head2 canonical
  1736.  
  1737.     $json = $json->canonical([$enable])
  1738.     
  1739.     $enabled = $json->get_canonical
  1740.  
  1741. If you want your own sorting routine, you can give a code referece
  1742. or a subroutine name to C<sort_by>. See to C<JSON::PP OWN METHODS>.
  1743.  
  1744. =head2 allow_nonref
  1745.  
  1746.     $json = $json->allow_nonref([$enable])
  1747.     
  1748.     $enabled = $json->get_allow_nonref
  1749.  
  1750. =head2 allow_unknown
  1751.  
  1752.     $json = $json->allow_unknown ([$enable])
  1753.     
  1754.     $enabled = $json->get_allow_unknown
  1755.  
  1756. =head2 allow_blessed
  1757.  
  1758.     $json = $json->allow_blessed([$enable])
  1759.     
  1760.     $enabled = $json->get_allow_blessed
  1761.  
  1762. =head2 convert_blessed
  1763.  
  1764.     $json = $json->convert_blessed([$enable])
  1765.     
  1766.     $enabled = $json->get_convert_blessed
  1767.  
  1768. =head2 filter_json_object
  1769.  
  1770.     $json = $json->filter_json_object([$coderef])
  1771.  
  1772. =head2 filter_json_single_key_object
  1773.  
  1774.     $json = $json->filter_json_single_key_object($key [=> $coderef])
  1775.  
  1776. =head2 shrink
  1777.  
  1778.     $json = $json->shrink([$enable])
  1779.     
  1780.     $enabled = $json->get_shrink
  1781.  
  1782. In JSON::XS, this flag resizes strings generated by either
  1783. C<encode> or C<decode> to their minimum size possible.
  1784. It will also try to downgrade any strings to octet-form if possible.
  1785.  
  1786. In JSON::PP, it is noop about resizing strings but tries
  1787. C<utf8::downgrade> to the returned string by C<encode>.
  1788. See to L<utf8>.
  1789.  
  1790. See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
  1791.  
  1792. =head2 max_depth
  1793.  
  1794.     $json = $json->max_depth([$maximum_nesting_depth])
  1795.     
  1796.     $max_depth = $json->get_max_depth
  1797.  
  1798. Sets the maximum nesting level (default C<512>) accepted while encoding
  1799. or decoding. If a higher nesting level is detected in JSON text or a Perl
  1800. data structure, then the encoder and decoder will stop and croak at that
  1801. point.
  1802.  
  1803. Nesting level is defined by number of hash- or arrayrefs that the encoder
  1804. needs to traverse to reach a given point or the number of C<{> or C<[>
  1805. characters without their matching closing parenthesis crossed to reach a
  1806. given character in a string.
  1807.  
  1808. If no argument is given, the highest possible setting will be used, which
  1809. is rarely useful.
  1810.  
  1811. See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
  1812.  
  1813. When a large value (100 or more) was set and it de/encodes a deep nested object/text,
  1814. it may raise a warning 'Deep recursion on subroutin' at the perl runtime phase.
  1815.  
  1816. =head2 max_size
  1817.  
  1818.     $json = $json->max_size([$maximum_string_size])
  1819.     
  1820.     $max_size = $json->get_max_size
  1821.  
  1822. Set the maximum length a JSON text may have (in bytes) where decoding is
  1823. being attempted. The default is C<0>, meaning no limit. When C<decode>
  1824. is called on a string that is longer then this many bytes, it will not
  1825. attempt to decode the string but throw an exception. This setting has no
  1826. effect on C<encode> (yet).
  1827.  
  1828. If no argument is given, the limit check will be deactivated (same as when
  1829. C<0> is specified).
  1830.  
  1831. See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
  1832.  
  1833. =head2 encode
  1834.  
  1835.     $json_text = $json->encode($perl_scalar)
  1836.  
  1837. =head2 decode
  1838.  
  1839.     $perl_scalar = $json->decode($json_text)
  1840.  
  1841. =head2 decode_prefix
  1842.  
  1843.     ($perl_scalar, $characters) = $json->decode_prefix($json_text)
  1844.  
  1845.  
  1846. =head1 INCREMENTAL PARSING
  1847.  
  1848. Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
  1849.  
  1850. In some cases, there is the need for incremental parsing of JSON texts.
  1851. This module does allow you to parse a JSON stream incrementally.
  1852. It does so by accumulating text until it has a full JSON object, which
  1853. it then can decode. This process is similar to using C<decode_prefix>
  1854. to see if a full JSON object is available, but is much more efficient
  1855. (and can be implemented with a minimum of method calls).
  1856.  
  1857. This module will only attempt to parse the JSON text once it is sure it
  1858. has enough text to get a decisive result, using a very simple but
  1859. truly incremental parser. This means that it sometimes won't stop as
  1860. early as the full parser, for example, it doesn't detect parenthese
  1861. mismatches. The only thing it guarantees is that it starts decoding as
  1862. soon as a syntactically valid JSON text has been seen. This means you need
  1863. to set resource limits (e.g. C<max_size>) to ensure the parser will stop
  1864. parsing in the presence if syntax errors.
  1865.  
  1866. The following methods implement this incremental parser.
  1867.  
  1868. =head2 incr_parse
  1869.  
  1870.     $json->incr_parse( [$string] ) # void context
  1871.     
  1872.     $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
  1873.     
  1874.     @obj_or_empty = $json->incr_parse( [$string] ) # list context
  1875.  
  1876. This is the central parsing function. It can both append new text and
  1877. extract objects from the stream accumulated so far (both of these
  1878. functions are optional).
  1879.  
  1880. If C<$string> is given, then this string is appended to the already
  1881. existing JSON fragment stored in the C<$json> object.
  1882.  
  1883. After that, if the function is called in void context, it will simply
  1884. return without doing anything further. This can be used to add more text
  1885. in as many chunks as you want.
  1886.  
  1887. If the method is called in scalar context, then it will try to extract
  1888. exactly I<one> JSON object. If that is successful, it will return this
  1889. object, otherwise it will return C<undef>. If there is a parse error,
  1890. this method will croak just as C<decode> would do (one can then use
  1891. C<incr_skip> to skip the errornous part). This is the most common way of
  1892. using the method.
  1893.  
  1894. And finally, in list context, it will try to extract as many objects
  1895. from the stream as it can find and return them, or the empty list
  1896. otherwise. For this to work, there must be no separators between the JSON
  1897. objects or arrays, instead they must be concatenated back-to-back. If
  1898. an error occurs, an exception will be raised as in the scalar context
  1899. case. Note that in this case, any previously-parsed JSON texts will be
  1900. lost.
  1901.  
  1902. Example: Parse some JSON arrays/objects in a given string and return them.
  1903.  
  1904.     my @objs = JSON->new->incr_parse ("[5][7][1,2]");
  1905.  
  1906. =head2 incr_text
  1907.  
  1908.     $lvalue_string = $json->incr_text
  1909.  
  1910. This method returns the currently stored JSON fragment as an lvalue, that
  1911. is, you can manipulate it. This I<only> works when a preceding call to
  1912. C<incr_parse> in I<scalar context> successfully returned an object. Under
  1913. all other circumstances you must not call this function (I mean it.
  1914. although in simple tests it might actually work, it I<will> fail under
  1915. real world conditions). As a special exception, you can also call this
  1916. method before having parsed anything.
  1917.  
  1918. This function is useful in two cases: a) finding the trailing text after a
  1919. JSON object or b) parsing multiple JSON objects separated by non-JSON text
  1920. (such as commas).
  1921.  
  1922.     $json->incr_text =~ s/\s*,\s*//;
  1923.  
  1924. In Perl 5.005, C<lvalue> attribute is not available.
  1925. You must write codes like the below:
  1926.  
  1927.     $string = $json->incr_text;
  1928.     $string =~ s/\s*,\s*//;
  1929.     $json->incr_text( $string );
  1930.  
  1931. =head2 incr_skip
  1932.  
  1933.     $json->incr_skip
  1934.  
  1935. This will reset the state of the incremental parser and will remove the
  1936. parsed text from the input buffer. This is useful after C<incr_parse>
  1937. died, in which case the input buffer and incremental parser state is left
  1938. unchanged, to skip the text parsed so far and to reset the parse state.
  1939.  
  1940. =head2 incr_reset
  1941.  
  1942.     $json->incr_reset
  1943.  
  1944. This completely resets the incremental parser, that is, after this call,
  1945. it will be as if the parser had never parsed anything.
  1946.  
  1947. This is useful if you want ot repeatedly parse JSON objects and want to
  1948. ignore any trailing data, which means you have to reset the parser after
  1949. each successful decode.
  1950.  
  1951. See to L<JSON::XS/INCREMENTAL PARSING> for examples.
  1952.  
  1953.  
  1954. =head1 JSON::PP OWN METHODS
  1955.  
  1956. =head2 allow_singlequote
  1957.  
  1958.     $json = $json->allow_singlequote([$enable])
  1959.  
  1960. If C<$enable> is true (or missing), then C<decode> will accept
  1961. JSON strings quoted by single quotations that are invalid JSON
  1962. format.
  1963.  
  1964.     $json->allow_singlequote->decode({"foo":'bar'});
  1965.     $json->allow_singlequote->decode({'foo':"bar"});
  1966.     $json->allow_singlequote->decode({'foo':'bar'});
  1967.  
  1968. As same as the C<relaxed> option, this option may be used to parse
  1969. application-specific files written by humans.
  1970.  
  1971.  
  1972. =head2 allow_barekey
  1973.  
  1974.     $json = $json->allow_barekey([$enable])
  1975.  
  1976. If C<$enable> is true (or missing), then C<decode> will accept
  1977. bare keys of JSON object that are invalid JSON format.
  1978.  
  1979. As same as the C<relaxed> option, this option may be used to parse
  1980. application-specific files written by humans.
  1981.  
  1982.     $json->allow_barekey->decode('{foo:"bar"}');
  1983.  
  1984. =head2 allow_bignum
  1985.  
  1986.     $json = $json->allow_bignum([$enable])
  1987.  
  1988. If C<$enable> is true (or missing), then C<decode> will convert
  1989. the big integer Perl cannot handle as integer into a L<Math::BigInt>
  1990. object and convert a floating number (any) into a L<Math::BigFloat>.
  1991.  
  1992. On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  1993. objects into JSON numbers with C<allow_blessed> enable.
  1994.  
  1995.    $json->allow_nonref->allow_blessed->allow_bignum;
  1996.    $bigfloat = $json->decode('2.000000000000000000000000001');
  1997.    print $json->encode($bigfloat);
  1998.    # => 2.000000000000000000000000001
  1999.  
  2000. See to L<JSON::XS/MAPPING> aboout the normal conversion of JSON number.
  2001.  
  2002. =head2 loose
  2003.  
  2004.     $json = $json->loose([$enable])
  2005.  
  2006. The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
  2007. and the module doesn't allow to C<decode> to these (except for \x2f).
  2008. If C<$enable> is true (or missing), then C<decode>  will accept these
  2009. unescaped strings.
  2010.  
  2011.     $json->loose->decode(qq|["abc
  2012.                                    def"]|);
  2013.  
  2014. See L<JSON::XS/SSECURITY CONSIDERATIONS>.
  2015.  
  2016. =head2 escape_slash
  2017.  
  2018.     $json = $json->escape_slash([$enable])
  2019.  
  2020. According to JSON Grammar, I<slash> (U+002F) is escaped. But default
  2021. JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
  2022.  
  2023. If C<$enable> is true (or missing), then C<encode> will escape slashes.
  2024.  
  2025. =head2 (OBSOLETED)as_nonblessed
  2026.  
  2027.     $json = $json->as_nonblessed
  2028.  
  2029. (OBSOLETED) If C<$enable> is true (or missing), then C<encode> will convert
  2030. a blessed hash reference or a blessed array reference (contains
  2031. other blessed references) into JSON members and arrays.
  2032.  
  2033. This feature is effective only when C<allow_blessed> is enable.
  2034.  
  2035. =head2 indent_length
  2036.  
  2037.     $json = $json->indent_length($length)
  2038.  
  2039. JSON::XS indent space length is 3 and cannot be changed.
  2040. JSON::PP set the indent space length with the given $length.
  2041. The default is 3. The acceptable range is 0 to 15.
  2042.  
  2043. =head2 sort_by
  2044.  
  2045.     $json = $json->sort_by($function_name)
  2046.     $json = $json->sort_by($subroutine_ref)
  2047.  
  2048. If $function_name or $subroutine_ref are set, its sort routine are used
  2049. in encoding JSON objects.
  2050.  
  2051.    $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
  2052.    # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  2053.  
  2054.    $js = $pc->sort_by('own_sort')->encode($obj);
  2055.    # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  2056.  
  2057.    sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
  2058.  
  2059. As the sorting routine runs in the JSON::PP scope, the given
  2060. subroutine name and the special variables C<$a>, C<$b> will begin
  2061. 'JSON::PP::'.
  2062.  
  2063. If $integer is set, then the effect is same as C<canonical> on.
  2064.  
  2065. =head1 INTERNAL
  2066.  
  2067. For developers.
  2068.  
  2069. =over
  2070.  
  2071. =item PP_encode_box
  2072.  
  2073. Returns
  2074.  
  2075.         {
  2076.             depth        => $depth,
  2077.             indent_count => $indent_count,
  2078.         }
  2079.  
  2080.  
  2081. =item PP_decode_box
  2082.  
  2083. Returns
  2084.  
  2085.         {
  2086.             text    => $text,
  2087.             at      => $at,
  2088.             ch      => $ch,
  2089.             len     => $len,
  2090.             depth   => $depth,
  2091.             encoding      => $encoding,
  2092.             is_valid_utf8 => $is_valid_utf8,
  2093.         };
  2094.  
  2095. =back
  2096.  
  2097. =head1 MAPPING
  2098.  
  2099. See to L<JSON::XS/MAPPING>.
  2100.  
  2101.  
  2102. =head1 UNICODE HANDLING ON PERLS
  2103.  
  2104. If you do not know about Unicode on Perl well,
  2105. please check L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
  2106.  
  2107. =head2 Perl 5.8 and later
  2108.  
  2109. Perl can handle Unicode and the JSON::PP de/encode methods also work properly.
  2110.  
  2111.     $json->allow_nonref->encode(chr hex 3042);
  2112.     $json->allow_nonref->encode(chr hex 12345);
  2113.  
  2114. Reuturns C<"\u3042"> and C<"\ud808\udf45"> respectively.
  2115.  
  2116.     $json->allow_nonref->decode('"\u3042"');
  2117.     $json->allow_nonref->decode('"\ud808\udf45"');
  2118.  
  2119. Returns UTF-8 encoded strings with UTF8 flag, regarded as C<U+3042> and C<U+12345>.
  2120.  
  2121. Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in C<join> was broken,
  2122. so JSON::PP wraps the C<join> with a subroutine. Thus JSON::PP works slow in the versions.
  2123.  
  2124.  
  2125. =head2 Perl 5.6
  2126.  
  2127. Perl can handle Unicode and the JSON::PP de/encode methods also work.
  2128.  
  2129. =head2 Perl 5.005
  2130.  
  2131. Perl 5.005 is a byte sementics world -- all strings are sequences of bytes.
  2132. That means the unicode handling is not available.
  2133.  
  2134. In encoding,
  2135.  
  2136.     $json->allow_nonref->encode(chr hex 3042);  # hex 3042 is 12354.
  2137.     $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
  2138.  
  2139. Returns C<B> and C<E>, as C<chr> takes a value more than 255, it treats
  2140. as C<$value % 256>, so the above codes are equivalent to :
  2141.  
  2142.     $json->allow_nonref->encode(chr 66);
  2143.     $json->allow_nonref->encode(chr 69);
  2144.  
  2145. In decoding,
  2146.  
  2147.     $json->decode('"\u00e3\u0081\u0082"');
  2148.  
  2149. The returned is a byte sequence C<0xE3 0x81 0x82> for UTF-8 encoded
  2150. japanese character (C<HIRAGANA LETTER A>).
  2151. And if it is represented in Unicode code point, C<U+3042>.
  2152.  
  2153. Next, 
  2154.  
  2155.     $json->decode('"\u3042"');
  2156.  
  2157. We ordinary expect the returned value is a Unicode character C<U+3042>.
  2158. But here is 5.005 world. This is C<0xE3 0x81 0x82>.
  2159.  
  2160.     $json->decode('"\ud808\udf45"');
  2161.  
  2162. This is not a character C<U+12345> but bytes - C<0xf0 0x92 0x8d 0x85>.
  2163.  
  2164.  
  2165. =head1 TODO
  2166.  
  2167. =over
  2168.  
  2169. =item speed
  2170.  
  2171. =item memory saving
  2172.  
  2173. =back
  2174.  
  2175.  
  2176. =head1 SEE ALSO
  2177.  
  2178. Most of the document are copied and modified from JSON::XS doc.
  2179.  
  2180. L<JSON::XS>
  2181.  
  2182. RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>)
  2183.  
  2184. =head1 AUTHOR
  2185.  
  2186. Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  2187.  
  2188.  
  2189. =head1 COPYRIGHT AND LICENSE
  2190.  
  2191. Copyright 2007-2010 by Makamaka Hannyaharamitu
  2192.  
  2193. This library is free software; you can redistribute it and/or modify
  2194. it under the same terms as Perl itself. 
  2195.  
  2196. =cut
  2197.