- add sources.
[platform/framework/web/crosswalk.git] / src / third_party / JSON / JSON-2.59 / blib / lib / JSON / backportPP.pm
1 package # This is JSON::backportPP
2     JSON::PP;
3
4 # JSON-2.0
5
6 use 5.005;
7 use strict;
8 use base qw(Exporter);
9 use overload ();
10
11 use Carp ();
12 use B ();
13 #use Devel::Peek;
14
15 use vars qw($VERSION);
16 $VERSION = '2.27202';
17
18 @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
19
20 # instead of hash-access, i tried index-access for speed.
21 # but this method is not faster than what i expected. so it will be changed.
22
23 use constant P_ASCII                => 0;
24 use constant P_LATIN1               => 1;
25 use constant P_UTF8                 => 2;
26 use constant P_INDENT               => 3;
27 use constant P_CANONICAL            => 4;
28 use constant P_SPACE_BEFORE         => 5;
29 use constant P_SPACE_AFTER          => 6;
30 use constant P_ALLOW_NONREF         => 7;
31 use constant P_SHRINK               => 8;
32 use constant P_ALLOW_BLESSED        => 9;
33 use constant P_CONVERT_BLESSED      => 10;
34 use constant P_RELAXED              => 11;
35
36 use constant P_LOOSE                => 12;
37 use constant P_ALLOW_BIGNUM         => 13;
38 use constant P_ALLOW_BAREKEY        => 14;
39 use constant P_ALLOW_SINGLEQUOTE    => 15;
40 use constant P_ESCAPE_SLASH         => 16;
41 use constant P_AS_NONBLESSED        => 17;
42
43 use constant P_ALLOW_UNKNOWN        => 18;
44
45 use constant OLD_PERL => $] < 5.008 ? 1 : 0;
46
47 BEGIN {
48     my @xs_compati_bit_properties = qw(
49             latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
50             allow_blessed convert_blessed relaxed allow_unknown
51     );
52     my @pp_bit_properties = qw(
53             allow_singlequote allow_bignum loose
54             allow_barekey escape_slash as_nonblessed
55     );
56
57     # Perl version check, Unicode handling is enable?
58     # Helper module sets @JSON::PP::_properties.
59     if ($] < 5.008 ) {
60         my $helper = $] >= 5.006 ? 'JSON::backportPP::Compat5006' : 'JSON::backportPP::Compat5005';
61         eval qq| require $helper |;
62         if ($@) { Carp::croak $@; }
63     }
64
65     for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
66         my $flag_name = 'P_' . uc($name);
67
68         eval qq/
69             sub $name {
70                 my \$enable = defined \$_[1] ? \$_[1] : 1;
71
72                 if (\$enable) {
73                     \$_[0]->{PROPS}->[$flag_name] = 1;
74                 }
75                 else {
76                     \$_[0]->{PROPS}->[$flag_name] = 0;
77                 }
78
79                 \$_[0];
80             }
81
82             sub get_$name {
83                 \$_[0]->{PROPS}->[$flag_name] ? 1 : '';
84             }
85         /;
86     }
87
88 }
89
90
91
92 # Functions
93
94 my %encode_allow_method
95      = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash
96                           allow_blessed convert_blessed indent indent_length allow_bignum
97                           as_nonblessed
98                         /;
99 my %decode_allow_method
100      = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum
101                           allow_barekey max_size relaxed/;
102
103
104 my $JSON; # cache
105
106 sub encode_json ($) { # encode
107     ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
108 }
109
110
111 sub decode_json { # decode
112     ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
113 }
114
115 # Obsoleted
116
117 sub to_json($) {
118    Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
119 }
120
121
122 sub from_json($) {
123    Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
124 }
125
126
127 # Methods
128
129 sub new {
130     my $class = shift;
131     my $self  = {
132         max_depth   => 512,
133         max_size    => 0,
134         indent      => 0,
135         FLAGS       => 0,
136         fallback      => sub { encode_error('Invalid value. JSON can only reference.') },
137         indent_length => 3,
138     };
139
140     bless $self, $class;
141 }
142
143
144 sub encode {
145     return $_[0]->PP_encode_json($_[1]);
146 }
147
148
149 sub decode {
150     return $_[0]->PP_decode_json($_[1], 0x00000000);
151 }
152
153
154 sub decode_prefix {
155     return $_[0]->PP_decode_json($_[1], 0x00000001);
156 }
157
158
159 # accessor
160
161
162 # pretty printing
163
164 sub pretty {
165     my ($self, $v) = @_;
166     my $enable = defined $v ? $v : 1;
167
168     if ($enable) { # indent_length(3) for JSON::XS compatibility
169         $self->indent(1)->indent_length(3)->space_before(1)->space_after(1);
170     }
171     else {
172         $self->indent(0)->space_before(0)->space_after(0);
173     }
174
175     $self;
176 }
177
178 # etc
179
180 sub max_depth {
181     my $max  = defined $_[1] ? $_[1] : 0x80000000;
182     $_[0]->{max_depth} = $max;
183     $_[0];
184 }
185
186
187 sub get_max_depth { $_[0]->{max_depth}; }
188
189
190 sub max_size {
191     my $max  = defined $_[1] ? $_[1] : 0;
192     $_[0]->{max_size} = $max;
193     $_[0];
194 }
195
196
197 sub get_max_size { $_[0]->{max_size}; }
198
199
200 sub filter_json_object {
201     $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0;
202     $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
203     $_[0];
204 }
205
206 sub filter_json_single_key_object {
207     if (@_ > 1) {
208         $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
209     }
210     $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
211     $_[0];
212 }
213
214 sub indent_length {
215     if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
216         Carp::carp "The acceptable range of indent_length() is 0 to 15.";
217     }
218     else {
219         $_[0]->{indent_length} = $_[1];
220     }
221     $_[0];
222 }
223
224 sub get_indent_length {
225     $_[0]->{indent_length};
226 }
227
228 sub sort_by {
229     $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
230     $_[0];
231 }
232
233 sub allow_bigint {
234     Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted.");
235 }
236
237 ###############################
238
239 ###
240 ### Perl => JSON
241 ###
242
243
244 { # Convert
245
246     my $max_depth;
247     my $indent;
248     my $ascii;
249     my $latin1;
250     my $utf8;
251     my $space_before;
252     my $space_after;
253     my $canonical;
254     my $allow_blessed;
255     my $convert_blessed;
256
257     my $indent_length;
258     my $escape_slash;
259     my $bignum;
260     my $as_nonblessed;
261
262     my $depth;
263     my $indent_count;
264     my $keysort;
265
266
267     sub PP_encode_json {
268         my $self = shift;
269         my $obj  = shift;
270
271         $indent_count = 0;
272         $depth        = 0;
273
274         my $idx = $self->{PROPS};
275
276         ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
277             $convert_blessed, $escape_slash, $bignum, $as_nonblessed)
278          = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
279                     P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED];
280
281         ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
282
283         $keysort = $canonical ? sub { $a cmp $b } : undef;
284
285         if ($self->{sort_by}) {
286             $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
287                      : $self->{sort_by} =~ /\D+/       ? $self->{sort_by}
288                      : sub { $a cmp $b };
289         }
290
291         encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
292              if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]);
293
294         my $str  = $self->object_to_json($obj);
295
296         $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
297
298         unless ($ascii or $latin1 or $utf8) {
299             utf8::upgrade($str);
300         }
301
302         if ($idx->[ P_SHRINK ]) {
303             utf8::downgrade($str, 1);
304         }
305
306         return $str;
307     }
308
309
310     sub object_to_json {
311         my ($self, $obj) = @_;
312         my $type = ref($obj);
313
314         if($type eq 'HASH'){
315             return $self->hash_to_json($obj);
316         }
317         elsif($type eq 'ARRAY'){
318             return $self->array_to_json($obj);
319         }
320         elsif ($type) { # blessed object?
321             if (blessed($obj)) {
322
323                 return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
324
325                 if ( $convert_blessed and $obj->can('TO_JSON') ) {
326                     my $result = $obj->TO_JSON();
327                     if ( defined $result and ref( $result ) ) {
328                         if ( refaddr( $obj ) eq refaddr( $result ) ) {
329                             encode_error( sprintf(
330                                 "%s::TO_JSON method returned same object as was passed instead of a new one",
331                                 ref $obj
332                             ) );
333                         }
334                     }
335
336                     return $self->object_to_json( $result );
337                 }
338
339                 return "$obj" if ( $bignum and _is_bignum($obj) );
340                 return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed.
341
342                 encode_error( sprintf("encountered object '%s', but neither allow_blessed "
343                     . "nor convert_blessed settings are enabled", $obj)
344                 ) unless ($allow_blessed);
345
346                 return 'null';
347             }
348             else {
349                 return $self->value_to_json($obj);
350             }
351         }
352         else{
353             return $self->value_to_json($obj);
354         }
355     }
356
357
358     sub hash_to_json {
359         my ($self, $obj) = @_;
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         for my $k ( _sort( $obj ) ) {
369             if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized
370             push @res, string_to_json( $self, $k )
371                           .  $del
372                           . ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) );
373         }
374
375         --$depth;
376         $self->_down_indent() if ($indent);
377
378         return   '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' )  . '}';
379     }
380
381
382     sub array_to_json {
383         my ($self, $obj) = @_;
384         my @res;
385
386         encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
387                                          if (++$depth > $max_depth);
388
389         my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
390
391         for my $v (@$obj){
392             push @res, $self->object_to_json($v) || $self->value_to_json($v);
393         }
394
395         --$depth;
396         $self->_down_indent() if ($indent);
397
398         return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']';
399     }
400
401
402     sub value_to_json {
403         my ($self, $value) = @_;
404
405         return 'null' if(!defined $value);
406
407         my $b_obj = B::svref_2object(\$value);  # for round trip problem
408         my $flags = $b_obj->FLAGS;
409
410         return $value # as is 
411             if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
412
413         my $type = ref($value);
414
415         if(!$type){
416             return string_to_json($self, $value);
417         }
418         elsif( blessed($value) and  $value->isa('JSON::PP::Boolean') ){
419             return $$value == 1 ? 'true' : 'false';
420         }
421         elsif ($type) {
422             if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
423                 return $self->value_to_json("$value");
424             }
425
426             if ($type eq 'SCALAR' and defined $$value) {
427                 return   $$value eq '1' ? 'true'
428                        : $$value eq '0' ? 'false'
429                        : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
430                        : encode_error("cannot encode reference to scalar");
431             }
432
433              if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
434                  return 'null';
435              }
436              else {
437                  if ( $type eq 'SCALAR' or $type eq 'REF' ) {
438                     encode_error("cannot encode reference to scalar");
439                  }
440                  else {
441                     encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
442                  }
443              }
444
445         }
446         else {
447             return $self->{fallback}->($value)
448                  if ($self->{fallback} and ref($self->{fallback}) eq 'CODE');
449             return 'null';
450         }
451
452     }
453
454
455     my %esc = (
456         "\n" => '\n',
457         "\r" => '\r',
458         "\t" => '\t',
459         "\f" => '\f',
460         "\b" => '\b',
461         "\"" => '\"',
462         "\\" => '\\\\',
463         "\'" => '\\\'',
464     );
465
466
467     sub string_to_json {
468         my ($self, $arg) = @_;
469
470         $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
471         $arg =~ s/\//\\\//g if ($escape_slash);
472         $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
473
474         if ($ascii) {
475             $arg = JSON_PP_encode_ascii($arg);
476         }
477
478         if ($latin1) {
479             $arg = JSON_PP_encode_latin1($arg);
480         }
481
482         if ($utf8) {
483             utf8::encode($arg);
484         }
485
486         return '"' . $arg . '"';
487     }
488
489
490     sub blessed_to_json {
491         my $reftype = reftype($_[1]) || '';
492         if ($reftype eq 'HASH') {
493             return $_[0]->hash_to_json($_[1]);
494         }
495         elsif ($reftype eq 'ARRAY') {
496             return $_[0]->array_to_json($_[1]);
497         }
498         else {
499             return 'null';
500         }
501     }
502
503
504     sub encode_error {
505         my $error  = shift;
506         Carp::croak "$error";
507     }
508
509
510     sub _sort {
511         defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]};
512     }
513
514
515     sub _up_indent {
516         my $self  = shift;
517         my $space = ' ' x $indent_length;
518
519         my ($pre,$post) = ('','');
520
521         $post = "\n" . $space x $indent_count;
522
523         $indent_count++;
524
525         $pre = "\n" . $space x $indent_count;
526
527         return ($pre,$post);
528     }
529
530
531     sub _down_indent { $indent_count--; }
532
533
534     sub PP_encode_box {
535         {
536             depth        => $depth,
537             indent_count => $indent_count,
538         };
539     }
540
541 } # Convert
542
543
544 sub _encode_ascii {
545     join('',
546         map {
547             $_ <= 127 ?
548                 chr($_) :
549             $_ <= 65535 ?
550                 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
551         } unpack('U*', $_[0])
552     );
553 }
554
555
556 sub _encode_latin1 {
557     join('',
558         map {
559             $_ <= 255 ?
560                 chr($_) :
561             $_ <= 65535 ?
562                 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
563         } unpack('U*', $_[0])
564     );
565 }
566
567
568 sub _encode_surrogates { # from perlunicode
569     my $uni = $_[0] - 0x10000;
570     return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
571 }
572
573
574 sub _is_bignum {
575     $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
576 }
577
578
579
580 #
581 # JSON => Perl
582 #
583
584 my $max_intsize;
585
586 BEGIN {
587     my $checkint = 1111;
588     for my $d (5..64) {
589         $checkint .= 1;
590         my $int   = eval qq| $checkint |;
591         if ($int =~ /[eE]/) {
592             $max_intsize = $d - 1;
593             last;
594         }
595     }
596 }
597
598 { # PARSE 
599
600     my %escapes = ( #  by Jeremy Muhlich <jmuhlich [at] bitflood.org>
601         b    => "\x8",
602         t    => "\x9",
603         n    => "\xA",
604         f    => "\xC",
605         r    => "\xD",
606         '\\' => '\\',
607         '"'  => '"',
608         '/'  => '/',
609     );
610
611     my $text; # json data
612     my $at;   # offset
613     my $ch;   # 1chracter
614     my $len;  # text length (changed according to UTF8 or NON UTF8)
615     # INTERNAL
616     my $depth;          # nest counter
617     my $encoding;       # json text encoding
618     my $is_valid_utf8;  # temp variable
619     my $utf8_len;       # utf8 byte length
620     # FLAGS
621     my $utf8;           # must be utf8
622     my $max_depth;      # max nest number of objects and arrays
623     my $max_size;
624     my $relaxed;
625     my $cb_object;
626     my $cb_sk_object;
627
628     my $F_HOOK;
629
630     my $allow_bigint;   # using Math::BigInt
631     my $singlequote;    # loosely quoting
632     my $loose;          # 
633     my $allow_barekey;  # bareKey
634
635     # $opt flag
636     # 0x00000001 .... decode_prefix
637     # 0x10000000 .... incr_parse
638
639     sub PP_decode_json {
640         my ($self, $opt); # $opt is an effective flag during this decode_json.
641
642         ($self, $text, $opt) = @_;
643
644         ($at, $ch, $depth) = (0, '', 0);
645
646         if ( !defined $text or ref $text ) {
647             decode_error("malformed JSON string, neither array, object, number, string or atom");
648         }
649
650         my $idx = $self->{PROPS};
651
652         ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote)
653             = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE];
654
655         if ( $utf8 ) {
656             utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
657         }
658         else {
659             utf8::upgrade( $text );
660         }
661
662         $len = length $text;
663
664         ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
665              = @{$self}{qw/max_depth  max_size cb_object cb_sk_object F_HOOK/};
666
667         if ($max_size > 1) {
668             use bytes;
669             my $bytes = length $text;
670             decode_error(
671                 sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
672                     , $bytes, $max_size), 1
673             ) if ($bytes > $max_size);
674         }
675
676         # Currently no effect
677         # should use regexp
678         my @octets = unpack('C4', $text);
679         $encoding =   ( $octets[0] and  $octets[1]) ? 'UTF-8'
680                     : (!$octets[0] and  $octets[1]) ? 'UTF-16BE'
681                     : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
682                     : ( $octets[2]                ) ? 'UTF-16LE'
683                     : (!$octets[2]                ) ? 'UTF-32LE'
684                     : 'unknown';
685
686         white(); # remove head white space
687
688         my $valid_start = defined $ch; # Is there a first character for JSON structure?
689
690         my $result = value();
691
692         return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse
693
694         decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start;
695
696         if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) {
697                 decode_error(
698                 'JSON text must be an object or array (but found number, string, true, false or null,'
699                        . ' use allow_nonref to allow this)', 1);
700         }
701
702         Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
703
704         my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
705
706         white(); # remove tail white space
707
708         if ( $ch ) {
709             return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix
710             decode_error("garbage after JSON object");
711         }
712
713         ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result;
714     }
715
716
717     sub next_chr {
718         return $ch = undef if($at >= $len);
719         $ch = substr($text, $at++, 1);
720     }
721
722
723     sub value {
724         white();
725         return          if(!defined $ch);
726         return object() if($ch eq '{');
727         return array()  if($ch eq '[');
728         return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
729         return number() if($ch =~ /[0-9]/ or $ch eq '-');
730         return word();
731     }
732
733     sub string {
734         my ($i, $s, $t, $u);
735         my $utf16;
736         my $is_utf8;
737
738         ($is_valid_utf8, $utf8_len) = ('', 0);
739
740         $s = ''; # basically UTF8 flag on
741
742         if($ch eq '"' or ($singlequote and $ch eq "'")){
743             my $boundChar = $ch;
744
745             OUTER: while( defined(next_chr()) ){
746
747                 if($ch eq $boundChar){
748                     next_chr();
749
750                     if ($utf16) {
751                         decode_error("missing low surrogate character in surrogate pair");
752                     }
753
754                     utf8::decode($s) if($is_utf8);
755
756                     return $s;
757                 }
758                 elsif($ch eq '\\'){
759                     next_chr();
760                     if(exists $escapes{$ch}){
761                         $s .= $escapes{$ch};
762                     }
763                     elsif($ch eq 'u'){ # UNICODE handling
764                         my $u = '';
765
766                         for(1..4){
767                             $ch = next_chr();
768                             last OUTER if($ch !~ /[0-9a-fA-F]/);
769                             $u .= $ch;
770                         }
771
772                         # U+D800 - U+DBFF
773                         if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
774                             $utf16 = $u;
775                         }
776                         # U+DC00 - U+DFFF
777                         elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
778                             unless (defined $utf16) {
779                                 decode_error("missing high surrogate character in surrogate pair");
780                             }
781                             $is_utf8 = 1;
782                             $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
783                             $utf16 = undef;
784                         }
785                         else {
786                             if (defined $utf16) {
787                                 decode_error("surrogate pair expected");
788                             }
789
790                             if ( ( my $hex = hex( $u ) ) > 127 ) {
791                                 $is_utf8 = 1;
792                                 $s .= JSON_PP_decode_unicode($u) || next;
793                             }
794                             else {
795                                 $s .= chr $hex;
796                             }
797                         }
798
799                     }
800                     else{
801                         unless ($loose) {
802                             $at -= 2;
803                             decode_error('illegal backslash escape sequence in string');
804                         }
805                         $s .= $ch;
806                     }
807                 }
808                 else{
809
810                     if ( ord $ch  > 127 ) {
811                         if ( $utf8 ) {
812                             unless( $ch = is_valid_utf8($ch) ) {
813                                 $at -= 1;
814                                 decode_error("malformed UTF-8 character in JSON string");
815                             }
816                             else {
817                                 $at += $utf8_len - 1;
818                             }
819                         }
820                         else {
821                             utf8::encode( $ch );
822                         }
823
824                         $is_utf8 = 1;
825                     }
826
827                     if (!$loose) {
828                         if ($ch =~ /[\x00-\x1f\x22\x5c]/)  { # '/' ok
829                             $at--;
830                             decode_error('invalid character encountered while parsing JSON string');
831                         }
832                     }
833
834                     $s .= $ch;
835                 }
836             }
837         }
838
839         decode_error("unexpected end of string while parsing JSON string");
840     }
841
842
843     sub white {
844         while( defined $ch  ){
845             if($ch le ' '){
846                 next_chr();
847             }
848             elsif($ch eq '/'){
849                 next_chr();
850                 if(defined $ch and $ch eq '/'){
851                     1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
852                 }
853                 elsif(defined $ch and $ch eq '*'){
854                     next_chr();
855                     while(1){
856                         if(defined $ch){
857                             if($ch eq '*'){
858                                 if(defined(next_chr()) and $ch eq '/'){
859                                     next_chr();
860                                     last;
861                                 }
862                             }
863                             else{
864                                 next_chr();
865                             }
866                         }
867                         else{
868                             decode_error("Unterminated comment");
869                         }
870                     }
871                     next;
872                 }
873                 else{
874                     $at--;
875                     decode_error("malformed JSON string, neither array, object, number, string or atom");
876                 }
877             }
878             else{
879                 if ($relaxed and $ch eq '#') { # correctly?
880                     pos($text) = $at;
881                     $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
882                     $at = pos($text);
883                     next_chr;
884                     next;
885                 }
886
887                 last;
888             }
889         }
890     }
891
892
893     sub array {
894         my $a  = $_[0] || []; # you can use this code to use another array ref object.
895
896         decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
897                                                     if (++$depth > $max_depth);
898
899         next_chr();
900         white();
901
902         if(defined $ch and $ch eq ']'){
903             --$depth;
904             next_chr();
905             return $a;
906         }
907         else {
908             while(defined($ch)){
909                 push @$a, value();
910
911                 white();
912
913                 if (!defined $ch) {
914                     last;
915                 }
916
917                 if($ch eq ']'){
918                     --$depth;
919                     next_chr();
920                     return $a;
921                 }
922
923                 if($ch ne ','){
924                     last;
925                 }
926
927                 next_chr();
928                 white();
929
930                 if ($relaxed and $ch eq ']') {
931                     --$depth;
932                     next_chr();
933                     return $a;
934                 }
935
936             }
937         }
938
939         decode_error(", or ] expected while parsing array");
940     }
941
942
943     sub object {
944         my $o = $_[0] || {}; # you can use this code to use another hash ref object.
945         my $k;
946
947         decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
948                                                 if (++$depth > $max_depth);
949         next_chr();
950         white();
951
952         if(defined $ch and $ch eq '}'){
953             --$depth;
954             next_chr();
955             if ($F_HOOK) {
956                 return _json_object_hook($o);
957             }
958             return $o;
959         }
960         else {
961             while (defined $ch) {
962                 $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
963                 white();
964
965                 if(!defined $ch or $ch ne ':'){
966                     $at--;
967                     decode_error("':' expected");
968                 }
969
970                 next_chr();
971                 $o->{$k} = value();
972                 white();
973
974                 last if (!defined $ch);
975
976                 if($ch eq '}'){
977                     --$depth;
978                     next_chr();
979                     if ($F_HOOK) {
980                         return _json_object_hook($o);
981                     }
982                     return $o;
983                 }
984
985                 if($ch ne ','){
986                     last;
987                 }
988
989                 next_chr();
990                 white();
991
992                 if ($relaxed and $ch eq '}') {
993                     --$depth;
994                     next_chr();
995                     if ($F_HOOK) {
996                         return _json_object_hook($o);
997                     }
998                     return $o;
999                 }
1000
1001             }
1002
1003         }
1004
1005         $at--;
1006         decode_error(", or } expected while parsing object/hash");
1007     }
1008
1009
1010     sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
1011         my $key;
1012         while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){
1013             $key .= $ch;
1014             next_chr();
1015         }
1016         return $key;
1017     }
1018
1019
1020     sub word {
1021         my $word =  substr($text,$at-1,4);
1022
1023         if($word eq 'true'){
1024             $at += 3;
1025             next_chr;
1026             return $JSON::PP::true;
1027         }
1028         elsif($word eq 'null'){
1029             $at += 3;
1030             next_chr;
1031             return undef;
1032         }
1033         elsif($word eq 'fals'){
1034             $at += 3;
1035             if(substr($text,$at,1) eq 'e'){
1036                 $at++;
1037                 next_chr;
1038                 return $JSON::PP::false;
1039             }
1040         }
1041
1042         $at--; # for decode_error report
1043
1044         decode_error("'null' expected")  if ($word =~ /^n/);
1045         decode_error("'true' expected")  if ($word =~ /^t/);
1046         decode_error("'false' expected") if ($word =~ /^f/);
1047         decode_error("malformed JSON string, neither array, object, number, string or atom");
1048     }
1049
1050
1051     sub number {
1052         my $n    = '';
1053         my $v;
1054
1055         # According to RFC4627, hex or oct digits are invalid.
1056         if($ch eq '0'){
1057             my $peek = substr($text,$at,1);
1058             my $hex  = $peek =~ /[xX]/; # 0 or 1
1059
1060             if($hex){
1061                 decode_error("malformed number (leading zero must not be followed by another digit)");
1062                 ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/);
1063             }
1064             else{ # oct
1065                 ($n) = ( substr($text, $at) =~ /^([0-7]+)/);
1066                 if (defined $n and length $n > 1) {
1067                     decode_error("malformed number (leading zero must not be followed by another digit)");
1068                 }
1069             }
1070
1071             if(defined $n and length($n)){
1072                 if (!$hex and length($n) == 1) {
1073                    decode_error("malformed number (leading zero must not be followed by another digit)");
1074                 }
1075                 $at += length($n) + $hex;
1076                 next_chr;
1077                 return $hex ? hex($n) : oct($n);
1078             }
1079         }
1080
1081         if($ch eq '-'){
1082             $n = '-';
1083             next_chr;
1084             if (!defined $ch or $ch !~ /\d/) {
1085                 decode_error("malformed number (no digits after initial minus)");
1086             }
1087         }
1088
1089         while(defined $ch and $ch =~ /\d/){
1090             $n .= $ch;
1091             next_chr;
1092         }
1093
1094         if(defined $ch and $ch eq '.'){
1095             $n .= '.';
1096
1097             next_chr;
1098             if (!defined $ch or $ch !~ /\d/) {
1099                 decode_error("malformed number (no digits after decimal point)");
1100             }
1101             else {
1102                 $n .= $ch;
1103             }
1104
1105             while(defined(next_chr) and $ch =~ /\d/){
1106                 $n .= $ch;
1107             }
1108         }
1109
1110         if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
1111             $n .= $ch;
1112             next_chr;
1113
1114             if(defined($ch) and ($ch eq '+' or $ch eq '-')){
1115                 $n .= $ch;
1116                 next_chr;
1117                 if (!defined $ch or $ch =~ /\D/) {
1118                     decode_error("malformed number (no digits after exp sign)");
1119                 }
1120                 $n .= $ch;
1121             }
1122             elsif(defined($ch) and $ch =~ /\d/){
1123                 $n .= $ch;
1124             }
1125             else {
1126                 decode_error("malformed number (no digits after exp sign)");
1127             }
1128
1129             while(defined(next_chr) and $ch =~ /\d/){
1130                 $n .= $ch;
1131             }
1132
1133         }
1134
1135         $v .= $n;
1136
1137         if ($v !~ /[.eE]/ and length $v > $max_intsize) {
1138             if ($allow_bigint) { # from Adam Sussman
1139                 require Math::BigInt;
1140                 return Math::BigInt->new($v);
1141             }
1142             else {
1143                 return "$v";
1144             }
1145         }
1146         elsif ($allow_bigint) {
1147             require Math::BigFloat;
1148             return Math::BigFloat->new($v);
1149         }
1150
1151         return 0+$v;
1152     }
1153
1154
1155     sub is_valid_utf8 {
1156
1157         $utf8_len = $_[0] =~ /[\x00-\x7F]/  ? 1
1158                   : $_[0] =~ /[\xC2-\xDF]/  ? 2
1159                   : $_[0] =~ /[\xE0-\xEF]/  ? 3
1160                   : $_[0] =~ /[\xF0-\xF4]/  ? 4
1161                   : 0
1162                   ;
1163
1164         return unless $utf8_len;
1165
1166         my $is_valid_utf8 = substr($text, $at - 1, $utf8_len);
1167
1168         return ( $is_valid_utf8 =~ /^(?:
1169              [\x00-\x7F]
1170             |[\xC2-\xDF][\x80-\xBF]
1171             |[\xE0][\xA0-\xBF][\x80-\xBF]
1172             |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
1173             |[\xED][\x80-\x9F][\x80-\xBF]
1174             |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
1175             |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
1176             |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
1177             |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
1178         )$/x )  ? $is_valid_utf8 : '';
1179     }
1180
1181
1182     sub decode_error {
1183         my $error  = shift;
1184         my $no_rep = shift;
1185         my $str    = defined $text ? substr($text, $at) : '';
1186         my $mess   = '';
1187         my $type   = $] >= 5.008           ? 'U*'
1188                    : $] <  5.006           ? 'C*'
1189                    : utf8::is_utf8( $str ) ? 'U*' # 5.6
1190                    : 'C*'
1191                    ;
1192
1193         for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
1194             $mess .=  $c == 0x07 ? '\a'
1195                     : $c == 0x09 ? '\t'
1196                     : $c == 0x0a ? '\n'
1197                     : $c == 0x0d ? '\r'
1198                     : $c == 0x0c ? '\f'
1199                     : $c <  0x20 ? sprintf('\x{%x}', $c)
1200                     : $c == 0x5c ? '\\\\'
1201                     : $c <  0x80 ? chr($c)
1202                     : sprintf('\x{%x}', $c)
1203                     ;
1204             if ( length $mess >= 20 ) {
1205                 $mess .= '...';
1206                 last;
1207             }
1208         }
1209
1210         unless ( length $mess ) {
1211             $mess = '(end of string)';
1212         }
1213
1214         Carp::croak (
1215             $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
1216         );
1217
1218     }
1219
1220
1221     sub _json_object_hook {
1222         my $o    = $_[0];
1223         my @ks = keys %{$o};
1224
1225         if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
1226             my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
1227             if (@val == 1) {
1228                 return $val[0];
1229             }
1230         }
1231
1232         my @val = $cb_object->($o) if ($cb_object);
1233         if (@val == 0 or @val > 1) {
1234             return $o;
1235         }
1236         else {
1237             return $val[0];
1238         }
1239     }
1240
1241
1242     sub PP_decode_box {
1243         {
1244             text    => $text,
1245             at      => $at,
1246             ch      => $ch,
1247             len     => $len,
1248             depth   => $depth,
1249             encoding      => $encoding,
1250             is_valid_utf8 => $is_valid_utf8,
1251         };
1252     }
1253
1254 } # PARSE
1255
1256
1257 sub _decode_surrogates { # from perlunicode
1258     my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
1259     my $un  = pack('U*', $uni);
1260     utf8::encode( $un );
1261     return $un;
1262 }
1263
1264
1265 sub _decode_unicode {
1266     my $un = pack('U', hex shift);
1267     utf8::encode( $un );
1268     return $un;
1269 }
1270
1271 #
1272 # Setup for various Perl versions (the code from JSON::PP58)
1273 #
1274
1275 BEGIN {
1276
1277     unless ( defined &utf8::is_utf8 ) {
1278        require Encode;
1279        *utf8::is_utf8 = *Encode::is_utf8;
1280     }
1281
1282     if ( $] >= 5.008 ) {
1283         *JSON::PP::JSON_PP_encode_ascii      = \&_encode_ascii;
1284         *JSON::PP::JSON_PP_encode_latin1     = \&_encode_latin1;
1285         *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
1286         *JSON::PP::JSON_PP_decode_unicode    = \&_decode_unicode;
1287     }
1288
1289     if ($] >= 5.008 and $] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken.
1290         package # hide from PAUSE
1291           JSON::PP;
1292         require subs;
1293         subs->import('join');
1294         eval q|
1295             sub join {
1296                 return '' if (@_ < 2);
1297                 my $j   = shift;
1298                 my $str = shift;
1299                 for (@_) { $str .= $j . $_; }
1300                 return $str;
1301             }
1302         |;
1303     }
1304
1305
1306     sub JSON::PP::incr_parse {
1307         local $Carp::CarpLevel = 1;
1308         ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ );
1309     }
1310
1311
1312     sub JSON::PP::incr_skip {
1313         ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip;
1314     }
1315
1316
1317     sub JSON::PP::incr_reset {
1318         ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset;
1319     }
1320
1321     eval q{
1322         sub JSON::PP::incr_text : lvalue {
1323             $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
1324
1325             if ( $_[0]->{_incr_parser}->{incr_parsing} ) {
1326                 Carp::croak("incr_text can not be called when the incremental parser already started parsing");
1327             }
1328             $_[0]->{_incr_parser}->{incr_text};
1329         }
1330     } if ( $] >= 5.006 );
1331
1332 } # Setup for various Perl versions (the code from JSON::PP58)
1333
1334
1335 ###############################
1336 # Utilities
1337 #
1338
1339 BEGIN {
1340     eval 'require Scalar::Util';
1341     unless($@){
1342         *JSON::PP::blessed = \&Scalar::Util::blessed;
1343         *JSON::PP::reftype = \&Scalar::Util::reftype;
1344         *JSON::PP::refaddr = \&Scalar::Util::refaddr;
1345     }
1346     else{ # This code is from Scalar::Util.
1347         # warn $@;
1348         eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
1349         *JSON::PP::blessed = sub {
1350             local($@, $SIG{__DIE__}, $SIG{__WARN__});
1351             ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
1352         };
1353         my %tmap = qw(
1354             B::NULL   SCALAR
1355             B::HV     HASH
1356             B::AV     ARRAY
1357             B::CV     CODE
1358             B::IO     IO
1359             B::GV     GLOB
1360             B::REGEXP REGEXP
1361         );
1362         *JSON::PP::reftype = sub {
1363             my $r = shift;
1364
1365             return undef unless length(ref($r));
1366
1367             my $t = ref(B::svref_2object($r));
1368
1369             return
1370                 exists $tmap{$t} ? $tmap{$t}
1371               : length(ref($$r)) ? 'REF'
1372               :                    'SCALAR';
1373         };
1374         *JSON::PP::refaddr = sub {
1375           return undef unless length(ref($_[0]));
1376
1377           my $addr;
1378           if(defined(my $pkg = blessed($_[0]))) {
1379             $addr .= bless $_[0], 'Scalar::Util::Fake';
1380             bless $_[0], $pkg;
1381           }
1382           else {
1383             $addr .= $_[0]
1384           }
1385
1386           $addr =~ /0x(\w+)/;
1387           local $^W;
1388           #no warnings 'portable';
1389           hex($1);
1390         }
1391     }
1392 }
1393
1394
1395 # shamelessly copied and modified from JSON::XS code.
1396
1397 $JSON::PP::true  = do { bless \(my $dummy = 1), "JSON::backportPP::Boolean" };
1398 $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::backportPP::Boolean" };
1399
1400 sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); }
1401
1402 sub true  { $JSON::PP::true  }
1403 sub false { $JSON::PP::false }
1404 sub null  { undef; }
1405
1406 ###############################
1407
1408 package JSON::backportPP::Boolean;
1409
1410 @JSON::backportPP::Boolean::ISA = ('JSON::PP::Boolean');
1411 use overload (
1412    "0+"     => sub { ${$_[0]} },
1413    "++"     => sub { $_[0] = ${$_[0]} + 1 },
1414    "--"     => sub { $_[0] = ${$_[0]} - 1 },
1415    fallback => 1,
1416 );
1417
1418
1419 ###############################
1420
1421 package # hide from PAUSE
1422   JSON::PP::IncrParser;
1423
1424 use strict;
1425
1426 use constant INCR_M_WS   => 0; # initial whitespace skipping
1427 use constant INCR_M_STR  => 1; # inside string
1428 use constant INCR_M_BS   => 2; # inside backslash
1429 use constant INCR_M_JSON => 3; # outside anything, count nesting
1430 use constant INCR_M_C0   => 4;
1431 use constant INCR_M_C1   => 5;
1432
1433 use vars qw($VERSION);
1434 $VERSION = '1.01';
1435
1436 my $unpack_format = $] < 5.006 ? 'C*' : 'U*';
1437
1438 sub new {
1439     my ( $class ) = @_;
1440
1441     bless {
1442         incr_nest    => 0,
1443         incr_text    => undef,
1444         incr_parsing => 0,
1445         incr_p       => 0,
1446     }, $class;
1447 }
1448
1449
1450 sub incr_parse {
1451     my ( $self, $coder, $text ) = @_;
1452
1453     $self->{incr_text} = '' unless ( defined $self->{incr_text} );
1454
1455     if ( defined $text ) {
1456         if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) {
1457             utf8::upgrade( $self->{incr_text} ) ;
1458             utf8::decode( $self->{incr_text} ) ;
1459         }
1460         $self->{incr_text} .= $text;
1461     }
1462
1463
1464     my $max_size = $coder->get_max_size;
1465
1466     if ( defined wantarray ) {
1467
1468         $self->{incr_mode} = INCR_M_WS unless defined $self->{incr_mode};
1469
1470         if ( wantarray ) {
1471             my @ret;
1472
1473             $self->{incr_parsing} = 1;
1474
1475             do {
1476                 push @ret, $self->_incr_parse( $coder, $self->{incr_text} );
1477
1478                 unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) {
1479                     $self->{incr_mode} = INCR_M_WS if $self->{incr_mode} != INCR_M_STR;
1480                 }
1481
1482             } until ( length $self->{incr_text} >= $self->{incr_p} );
1483
1484             $self->{incr_parsing} = 0;
1485
1486             return @ret;
1487         }
1488         else { # in scalar context
1489             $self->{incr_parsing} = 1;
1490             my $obj = $self->_incr_parse( $coder, $self->{incr_text} );
1491             $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans
1492             return $obj ? $obj : undef; # $obj is an empty string, parsing was completed.
1493         }
1494
1495     }
1496
1497 }
1498
1499
1500 sub _incr_parse {
1501     my ( $self, $coder, $text, $skip ) = @_;
1502     my $p = $self->{incr_p};
1503     my $restore = $p;
1504
1505     my @obj;
1506     my $len = length $text;
1507
1508     if ( $self->{incr_mode} == INCR_M_WS ) {
1509         while ( $len > $p ) {
1510             my $s = substr( $text, $p, 1 );
1511             $p++ and next if ( 0x20 >= unpack($unpack_format, $s) );
1512             $self->{incr_mode} = INCR_M_JSON;
1513             last;
1514        }
1515     }
1516
1517     while ( $len > $p ) {
1518         my $s = substr( $text, $p++, 1 );
1519
1520         if ( $s eq '"' ) {
1521             if (substr( $text, $p - 2, 1 ) eq '\\' ) {
1522                 next;
1523             }
1524
1525             if ( $self->{incr_mode} != INCR_M_STR  ) {
1526                 $self->{incr_mode} = INCR_M_STR;
1527             }
1528             else {
1529                 $self->{incr_mode} = INCR_M_JSON;
1530                 unless ( $self->{incr_nest} ) {
1531                     last;
1532                 }
1533             }
1534         }
1535
1536         if ( $self->{incr_mode} == INCR_M_JSON ) {
1537
1538             if ( $s eq '[' or $s eq '{' ) {
1539                 if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
1540                     Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
1541                 }
1542             }
1543             elsif ( $s eq ']' or $s eq '}' ) {
1544                 last if ( --$self->{incr_nest} <= 0 );
1545             }
1546             elsif ( $s eq '#' ) {
1547                 while ( $len > $p ) {
1548                     last if substr( $text, $p++, 1 ) eq "\n";
1549                 }
1550             }
1551
1552         }
1553
1554     }
1555
1556     $self->{incr_p} = $p;
1557
1558     return if ( $self->{incr_mode} == INCR_M_STR and not $self->{incr_nest} );
1559     return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 );
1560
1561     return '' unless ( length substr( $self->{incr_text}, 0, $p ) );
1562
1563     local $Carp::CarpLevel = 2;
1564
1565     $self->{incr_p} = $restore;
1566     $self->{incr_c} = $p;
1567
1568     my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 );
1569
1570     $self->{incr_text} = substr( $self->{incr_text}, $p );
1571     $self->{incr_p} = 0;
1572
1573     return $obj or '';
1574 }
1575
1576
1577 sub incr_text {
1578     if ( $_[0]->{incr_parsing} ) {
1579         Carp::croak("incr_text can not be called when the incremental parser already started parsing");
1580     }
1581     $_[0]->{incr_text};
1582 }
1583
1584
1585 sub incr_skip {
1586     my $self  = shift;
1587     $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} );
1588     $self->{incr_p} = 0;
1589 }
1590
1591
1592 sub incr_reset {
1593     my $self = shift;
1594     $self->{incr_text}    = undef;
1595     $self->{incr_p}       = 0;
1596     $self->{incr_mode}    = 0;
1597     $self->{incr_nest}    = 0;
1598     $self->{incr_parsing} = 0;
1599 }
1600
1601 ###############################
1602
1603
1604 1;
1605 __END__
1606 =pod
1607
1608 =head1 NAME
1609
1610 JSON::PP - JSON::XS compatible pure-Perl module.
1611
1612 =head1 SYNOPSIS
1613
1614  use JSON::PP;
1615
1616  # exported functions, they croak on error
1617  # and expect/generate UTF-8
1618
1619  $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
1620  $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
1621
1622  # OO-interface
1623
1624  $coder = JSON::PP->new->ascii->pretty->allow_nonref;
1625  
1626  $json_text   = $json->encode( $perl_scalar );
1627  $perl_scalar = $json->decode( $json_text );
1628  
1629  $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
1630  
1631  # Note that JSON version 2.0 and above will automatically use
1632  # JSON::XS or JSON::PP, so you should be able to just:
1633  
1634  use JSON;
1635
1636
1637 =head1 VERSION
1638
1639     2.27200
1640
1641 L<JSON::XS> 2.27 (~2.30) compatible.
1642
1643 =head1 DESCRIPTION
1644
1645 This module is L<JSON::XS> compatible pure Perl module.
1646 (Perl 5.8 or later is recommended)
1647
1648 JSON::XS is the fastest and most proper JSON module on CPAN.
1649 It is written by Marc Lehmann in C, so must be compiled and
1650 installed in the used environment.
1651
1652 JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
1653
1654
1655 =head2 FEATURES
1656
1657 =over
1658
1659 =item * correct unicode handling
1660
1661 This module knows how to handle Unicode (depending on Perl version).
1662
1663 See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> and
1664 L<UNICODE HANDLING ON PERLS>.
1665
1666
1667 =item * round-trip integrity
1668
1669 When you serialise a perl data structure using only data types
1670 supported by JSON and Perl, the deserialised data structure is
1671 identical on the Perl level. (e.g. the string "2.0" doesn't suddenly
1672 become "2" just because it looks like a number). There I<are> minor
1673 exceptions to this, read the MAPPING section below to learn about
1674 those.
1675
1676
1677 =item * strict checking of JSON correctness
1678
1679 There is no guessing, no generating of illegal JSON texts by default,
1680 and only JSON is accepted as input by default (the latter is a
1681 security feature). But when some options are set, loose checking
1682 features are available.
1683
1684 =back
1685
1686 =head1 FUNCTIONAL INTERFACE
1687
1688 Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
1689
1690 =head2 encode_json
1691
1692     $json_text = encode_json $perl_scalar
1693
1694 Converts the given Perl data structure to a UTF-8 encoded, binary string.
1695
1696 This function call is functionally identical to:
1697
1698     $json_text = JSON::PP->new->utf8->encode($perl_scalar)
1699
1700 =head2 decode_json
1701
1702     $perl_scalar = decode_json $json_text
1703
1704 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
1705 to parse that as an UTF-8 encoded JSON text, returning the resulting
1706 reference.
1707
1708 This function call is functionally identical to:
1709
1710     $perl_scalar = JSON::PP->new->utf8->decode($json_text)
1711
1712 =head2 JSON::PP::is_bool
1713
1714     $is_boolean = JSON::PP::is_bool($scalar)
1715
1716 Returns true if the passed scalar represents either JSON::PP::true or
1717 JSON::PP::false, two constants that act like C<1> and C<0> respectively
1718 and are also used to represent JSON C<true> and C<false> in Perl strings.
1719
1720 =head2 JSON::PP::true
1721
1722 Returns JSON true value which is blessed object.
1723 It C<isa> JSON::PP::Boolean object.
1724
1725 =head2 JSON::PP::false
1726
1727 Returns JSON false value which is blessed object.
1728 It C<isa> JSON::PP::Boolean object.
1729
1730 =head2 JSON::PP::null
1731
1732 Returns C<undef>.
1733
1734 See L<MAPPING>, below, for more information on how JSON values are mapped to
1735 Perl.
1736
1737
1738 =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
1739
1740 This section supposes that your perl version is 5.8 or later.
1741
1742 If you know a JSON text from an outer world - a network, a file content, and so on,
1743 is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
1744 with C<utf8> enable. And the decoded result will contain UNICODE characters.
1745
1746   # from network
1747   my $json        = JSON::PP->new->utf8;
1748   my $json_text   = CGI->new->param( 'json_data' );
1749   my $perl_scalar = $json->decode( $json_text );
1750   
1751   # from file content
1752   local $/;
1753   open( my $fh, '<', 'json.data' );
1754   $json_text   = <$fh>;
1755   $perl_scalar = decode_json( $json_text );
1756
1757 If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
1758
1759   use Encode;
1760   local $/;
1761   open( my $fh, '<', 'json.data' );
1762   my $encoding = 'cp932';
1763   my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
1764   
1765   # or you can write the below code.
1766   #
1767   # open( my $fh, "<:encoding($encoding)", 'json.data' );
1768   # $unicode_json_text = <$fh>;
1769
1770 In this case, C<$unicode_json_text> is of course UNICODE string.
1771 So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
1772 Instead of them, you use C<JSON> module object with C<utf8> disable.
1773
1774   $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
1775
1776 Or C<encode 'utf8'> and C<decode_json>:
1777
1778   $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
1779   # this way is not efficient.
1780
1781 And now, you want to convert your C<$perl_scalar> into JSON data and
1782 send it to an outer world - a network or a file content, and so on.
1783
1784 Your data usually contains UNICODE strings and you want the converted data to be encoded
1785 in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
1786
1787   print encode_json( $perl_scalar ); # to a network? file? or display?
1788   # or
1789   print $json->utf8->encode( $perl_scalar );
1790
1791 If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
1792 for some reason, then its characters are regarded as B<latin1> for perl
1793 (because it does not concern with your $encoding).
1794 You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
1795 Instead of them, you use C<JSON> module object with C<utf8> disable.
1796 Note that the resulted text is a UNICODE string but no problem to print it.
1797
1798   # $perl_scalar contains $encoding encoded string values
1799   $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
1800   # $unicode_json_text consists of characters less than 0x100
1801   print $unicode_json_text;
1802
1803 Or C<decode $encoding> all string values and C<encode_json>:
1804
1805   $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
1806   # ... do it to each string values, then encode_json
1807   $json_text = encode_json( $perl_scalar );
1808
1809 This method is a proper way but probably not efficient.
1810
1811 See to L<Encode>, L<perluniintro>.
1812
1813
1814 =head1 METHODS
1815
1816 Basically, check to L<JSON> or L<JSON::XS>.
1817
1818 =head2 new
1819
1820     $json = JSON::PP->new
1821
1822 Returns a new JSON::PP object that can be used to de/encode JSON
1823 strings.
1824
1825 All boolean flags described below are by default I<disabled>.
1826
1827 The mutators for flags all return the JSON object again and thus calls can
1828 be chained:
1829
1830    my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
1831    => {"a": [1, 2]}
1832
1833 =head2 ascii
1834
1835     $json = $json->ascii([$enable])
1836     
1837     $enabled = $json->get_ascii
1838
1839 If $enable is true (or missing), then the encode method will not generate characters outside
1840 the code range 0..127. Any Unicode characters outside that range will be escaped using either
1841 a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
1842 (See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>).
1843
1844 In Perl 5.005, there is no character having high value (more than 255).
1845 See to L<UNICODE HANDLING ON PERLS>.
1846
1847 If $enable is false, then the encode method will not escape Unicode characters unless
1848 required by the JSON syntax or other flags. This results in a faster and more compact format.
1849
1850   JSON::PP->new->ascii(1)->encode([chr 0x10401])
1851   => ["\ud801\udc01"]
1852
1853 =head2 latin1
1854
1855     $json = $json->latin1([$enable])
1856     
1857     $enabled = $json->get_latin1
1858
1859 If $enable is true (or missing), then the encode method will encode the resulting JSON
1860 text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
1861
1862 If $enable is false, then the encode method will not escape Unicode characters
1863 unless required by the JSON syntax or other flags.
1864
1865   JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
1866   => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
1867
1868 See to L<UNICODE HANDLING ON PERLS>.
1869
1870 =head2 utf8
1871
1872     $json = $json->utf8([$enable])
1873     
1874     $enabled = $json->get_utf8
1875
1876 If $enable is true (or missing), then the encode method will encode the JSON result
1877 into UTF-8, as required by many protocols, while the decode method expects to be handled
1878 an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
1879 characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
1880
1881 (In Perl 5.005, any character outside the range 0..255 does not exist.
1882 See to L<UNICODE HANDLING ON PERLS>.)
1883
1884 In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
1885 encoding families, as described in RFC4627.
1886
1887 If $enable is false, then the encode method will return the JSON string as a (non-encoded)
1888 Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
1889 (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
1890
1891 Example, output UTF-16BE-encoded JSON:
1892
1893   use Encode;
1894   $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
1895
1896 Example, decode UTF-32LE-encoded JSON:
1897
1898   use Encode;
1899   $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
1900
1901
1902 =head2 pretty
1903
1904     $json = $json->pretty([$enable])
1905
1906 This enables (or disables) all of the C<indent>, C<space_before> and
1907 C<space_after> flags in one call to generate the most readable
1908 (or most compact) form possible.
1909
1910 Equivalent to:
1911
1912    $json->indent->space_before->space_after
1913
1914 =head2 indent
1915
1916     $json = $json->indent([$enable])
1917     
1918     $enabled = $json->get_indent
1919
1920 The default indent space length is three.
1921 You can use C<indent_length> to change the length.
1922
1923 =head2 space_before
1924
1925     $json = $json->space_before([$enable])
1926     
1927     $enabled = $json->get_space_before
1928
1929 If C<$enable> is true (or missing), then the C<encode> method will add an extra
1930 optional space before the C<:> separating keys from values in JSON objects.
1931
1932 If C<$enable> is false, then the C<encode> method will not add any extra
1933 space at those places.
1934
1935 This setting has no effect when decoding JSON texts.
1936
1937 Example, space_before enabled, space_after and indent disabled:
1938
1939    {"key" :"value"}
1940
1941 =head2 space_after
1942
1943     $json = $json->space_after([$enable])
1944     
1945     $enabled = $json->get_space_after
1946
1947 If C<$enable> is true (or missing), then the C<encode> method will add an extra
1948 optional space after the C<:> separating keys from values in JSON objects
1949 and extra whitespace after the C<,> separating key-value pairs and array
1950 members.
1951
1952 If C<$enable> is false, then the C<encode> method will not add any extra
1953 space at those places.
1954
1955 This setting has no effect when decoding JSON texts.
1956
1957 Example, space_before and indent disabled, space_after enabled:
1958
1959    {"key": "value"}
1960
1961 =head2 relaxed
1962
1963     $json = $json->relaxed([$enable])
1964     
1965     $enabled = $json->get_relaxed
1966
1967 If C<$enable> is true (or missing), then C<decode> will accept some
1968 extensions to normal JSON syntax (see below). C<encode> will not be
1969 affected in anyway. I<Be aware that this option makes you accept invalid
1970 JSON texts as if they were valid!>. I suggest only to use this option to
1971 parse application-specific files written by humans (configuration files,
1972 resource files etc.)
1973
1974 If C<$enable> is false (the default), then C<decode> will only accept
1975 valid JSON texts.
1976
1977 Currently accepted extensions are:
1978
1979 =over 4
1980
1981 =item * list items can have an end-comma
1982
1983 JSON I<separates> array elements and key-value pairs with commas. This
1984 can be annoying if you write JSON texts manually and want to be able to
1985 quickly append elements, so this extension accepts comma at the end of
1986 such items not just between them:
1987
1988    [
1989       1,
1990       2, <- this comma not normally allowed
1991    ]
1992    {
1993       "k1": "v1",
1994       "k2": "v2", <- this comma not normally allowed
1995    }
1996
1997 =item * shell-style '#'-comments
1998
1999 Whenever JSON allows whitespace, shell-style comments are additionally
2000 allowed. They are terminated by the first carriage-return or line-feed
2001 character, after which more white-space and comments are allowed.
2002
2003   [
2004      1, # this comment not allowed in JSON
2005         # neither this one...
2006   ]
2007
2008 =back
2009
2010 =head2 canonical
2011
2012     $json = $json->canonical([$enable])
2013     
2014     $enabled = $json->get_canonical
2015
2016 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
2017 by sorting their keys. This is adding a comparatively high overhead.
2018
2019 If C<$enable> is false, then the C<encode> method will output key-value
2020 pairs in the order Perl stores them (which will likely change between runs
2021 of the same script).
2022
2023 This option is useful if you want the same data structure to be encoded as
2024 the same JSON text (given the same overall settings). If it is disabled,
2025 the same hash might be encoded differently even if contains the same data,
2026 as key-value pairs have no inherent ordering in Perl.
2027
2028 This setting has no effect when decoding JSON texts.
2029
2030 If you want your own sorting routine, you can give a code reference
2031 or a subroutine name to C<sort_by>. See to C<JSON::PP OWN METHODS>.
2032
2033 =head2 allow_nonref
2034
2035     $json = $json->allow_nonref([$enable])
2036     
2037     $enabled = $json->get_allow_nonref
2038
2039 If C<$enable> is true (or missing), then the C<encode> method can convert a
2040 non-reference into its corresponding string, number or null JSON value,
2041 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
2042 values instead of croaking.
2043
2044 If C<$enable> is false, then the C<encode> method will croak if it isn't
2045 passed an arrayref or hashref, as JSON texts must either be an object
2046 or array. Likewise, C<decode> will croak if given something that is not a
2047 JSON object or array.
2048
2049    JSON::PP->new->allow_nonref->encode ("Hello, World!")
2050    => "Hello, World!"
2051
2052 =head2 allow_unknown
2053
2054     $json = $json->allow_unknown ([$enable])
2055     
2056     $enabled = $json->get_allow_unknown
2057
2058 If $enable is true (or missing), then "encode" will *not* throw an
2059 exception when it encounters values it cannot represent in JSON (for
2060 example, filehandles) but instead will encode a JSON "null" value.
2061 Note that blessed objects are not included here and are handled
2062 separately by c<allow_nonref>.
2063
2064 If $enable is false (the default), then "encode" will throw an
2065 exception when it encounters anything it cannot encode as JSON.
2066
2067 This option does not affect "decode" in any way, and it is
2068 recommended to leave it off unless you know your communications
2069 partner.
2070
2071 =head2 allow_blessed
2072
2073     $json = $json->allow_blessed([$enable])
2074     
2075     $enabled = $json->get_allow_blessed
2076
2077 If C<$enable> is true (or missing), then the C<encode> method will not
2078 barf when it encounters a blessed reference. Instead, the value of the
2079 B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
2080 disabled or no C<TO_JSON> method found) or a representation of the
2081 object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
2082 encoded. Has no effect on C<decode>.
2083
2084 If C<$enable> is false (the default), then C<encode> will throw an
2085 exception when it encounters a blessed object.
2086
2087 =head2 convert_blessed
2088
2089     $json = $json->convert_blessed([$enable])
2090     
2091     $enabled = $json->get_convert_blessed
2092
2093 If C<$enable> is true (or missing), then C<encode>, upon encountering a
2094 blessed object, will check for the availability of the C<TO_JSON> method
2095 on the object's class. If found, it will be called in scalar context
2096 and the resulting scalar will be encoded instead of the object. If no
2097 C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
2098 to do.
2099
2100 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
2101 returns other blessed objects, those will be handled in the same
2102 way. C<TO_JSON> must take care of not causing an endless recursion cycle
2103 (== crash) in this case. The name of C<TO_JSON> was chosen because other
2104 methods called by the Perl core (== not by the user of the object) are
2105 usually in upper case letters and to avoid collisions with the C<to_json>
2106 function or method.
2107
2108 This setting does not yet influence C<decode> in any way.
2109
2110 If C<$enable> is false, then the C<allow_blessed> setting will decide what
2111 to do when a blessed object is found.
2112
2113 =head2 filter_json_object
2114
2115     $json = $json->filter_json_object([$coderef])
2116
2117 When C<$coderef> is specified, it will be called from C<decode> each
2118 time it decodes a JSON object. The only argument passed to the coderef
2119 is a reference to the newly-created hash. If the code references returns
2120 a single scalar (which need not be a reference), this value
2121 (i.e. a copy of that scalar to avoid aliasing) is inserted into the
2122 deserialised data structure. If it returns an empty list
2123 (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
2124 hash will be inserted. This setting can slow down decoding considerably.
2125
2126 When C<$coderef> is omitted or undefined, any existing callback will
2127 be removed and C<decode> will not change the deserialised hash in any
2128 way.
2129
2130 Example, convert all JSON objects into the integer 5:
2131
2132    my $js = JSON::PP->new->filter_json_object (sub { 5 });
2133    # returns [5]
2134    $js->decode ('[{}]'); # the given subroutine takes a hash reference.
2135    # throw an exception because allow_nonref is not enabled
2136    # so a lone 5 is not allowed.
2137    $js->decode ('{"a":1, "b":2}');
2138
2139 =head2 filter_json_single_key_object
2140
2141     $json = $json->filter_json_single_key_object($key [=> $coderef])
2142
2143 Works remotely similar to C<filter_json_object>, but is only called for
2144 JSON objects having a single key named C<$key>.
2145
2146 This C<$coderef> is called before the one specified via
2147 C<filter_json_object>, if any. It gets passed the single value in the JSON
2148 object. If it returns a single value, it will be inserted into the data
2149 structure. If it returns nothing (not even C<undef> but the empty list),
2150 the callback from C<filter_json_object> will be called next, as if no
2151 single-key callback were specified.
2152
2153 If C<$coderef> is omitted or undefined, the corresponding callback will be
2154 disabled. There can only ever be one callback for a given key.
2155
2156 As this callback gets called less often then the C<filter_json_object>
2157 one, decoding speed will not usually suffer as much. Therefore, single-key
2158 objects make excellent targets to serialise Perl objects into, especially
2159 as single-key JSON objects are as close to the type-tagged value concept
2160 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
2161 support this in any way, so you need to make sure your data never looks
2162 like a serialised Perl hash.
2163
2164 Typical names for the single object key are C<__class_whatever__>, or
2165 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
2166 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
2167 with real hashes.
2168
2169 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
2170 into the corresponding C<< $WIDGET{<id>} >> object:
2171
2172    # return whatever is in $WIDGET{5}:
2173    JSON::PP
2174       ->new
2175       ->filter_json_single_key_object (__widget__ => sub {
2176             $WIDGET{ $_[0] }
2177          })
2178       ->decode ('{"__widget__": 5')
2179
2180    # this can be used with a TO_JSON method in some "widget" class
2181    # for serialisation to json:
2182    sub WidgetBase::TO_JSON {
2183       my ($self) = @_;
2184
2185       unless ($self->{id}) {
2186          $self->{id} = ..get..some..id..;
2187          $WIDGET{$self->{id}} = $self;
2188       }
2189
2190       { __widget__ => $self->{id} }
2191    }
2192
2193 =head2 shrink
2194
2195     $json = $json->shrink([$enable])
2196     
2197     $enabled = $json->get_shrink
2198
2199 In JSON::XS, this flag resizes strings generated by either
2200 C<encode> or C<decode> to their minimum size possible.
2201 It will also try to downgrade any strings to octet-form if possible.
2202
2203 In JSON::PP, it is noop about resizing strings but tries
2204 C<utf8::downgrade> to the returned string by C<encode>.
2205 See to L<utf8>.
2206
2207 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
2208
2209 =head2 max_depth
2210
2211     $json = $json->max_depth([$maximum_nesting_depth])
2212     
2213     $max_depth = $json->get_max_depth
2214
2215 Sets the maximum nesting level (default C<512>) accepted while encoding
2216 or decoding. If a higher nesting level is detected in JSON text or a Perl
2217 data structure, then the encoder and decoder will stop and croak at that
2218 point.
2219
2220 Nesting level is defined by number of hash- or arrayrefs that the encoder
2221 needs to traverse to reach a given point or the number of C<{> or C<[>
2222 characters without their matching closing parenthesis crossed to reach a
2223 given character in a string.
2224
2225 If no argument is given, the highest possible setting will be used, which
2226 is rarely useful.
2227
2228 See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
2229
2230 When a large value (100 or more) was set and it de/encodes a deep nested object/text,
2231 it may raise a warning 'Deep recursion on subroutine' at the perl runtime phase.
2232
2233 =head2 max_size
2234
2235     $json = $json->max_size([$maximum_string_size])
2236     
2237     $max_size = $json->get_max_size
2238
2239 Set the maximum length a JSON text may have (in bytes) where decoding is
2240 being attempted. The default is C<0>, meaning no limit. When C<decode>
2241 is called on a string that is longer then this many bytes, it will not
2242 attempt to decode the string but throw an exception. This setting has no
2243 effect on C<encode> (yet).
2244
2245 If no argument is given, the limit check will be deactivated (same as when
2246 C<0> is specified).
2247
2248 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
2249
2250 =head2 encode
2251
2252     $json_text = $json->encode($perl_scalar)
2253
2254 Converts the given Perl data structure (a simple scalar or a reference
2255 to a hash or array) to its JSON representation. Simple scalars will be
2256 converted into JSON string or number sequences, while references to arrays
2257 become JSON arrays and references to hashes become JSON objects. Undefined
2258 Perl values (e.g. C<undef>) become JSON C<null> values.
2259 References to the integers C<0> and C<1> are converted into C<true> and C<false>.
2260
2261 =head2 decode
2262
2263     $perl_scalar = $json->decode($json_text)
2264
2265 The opposite of C<encode>: expects a JSON text and tries to parse it,
2266 returning the resulting simple scalar or reference. Croaks on error.
2267
2268 JSON numbers and strings become simple Perl scalars. JSON arrays become
2269 Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
2270 C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
2271 C<null> becomes C<undef>.
2272
2273 =head2 decode_prefix
2274
2275     ($perl_scalar, $characters) = $json->decode_prefix($json_text)
2276
2277 This works like the C<decode> method, but instead of raising an exception
2278 when there is trailing garbage after the first JSON object, it will
2279 silently stop parsing there and return the number of characters consumed
2280 so far.
2281
2282    JSON->new->decode_prefix ("[1] the tail")
2283    => ([], 3)
2284
2285 =head1 INCREMENTAL PARSING
2286
2287 Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
2288
2289 In some cases, there is the need for incremental parsing of JSON texts.
2290 This module does allow you to parse a JSON stream incrementally.
2291 It does so by accumulating text until it has a full JSON object, which
2292 it then can decode. This process is similar to using C<decode_prefix>
2293 to see if a full JSON object is available, but is much more efficient
2294 (and can be implemented with a minimum of method calls).
2295
2296 This module will only attempt to parse the JSON text once it is sure it
2297 has enough text to get a decisive result, using a very simple but
2298 truly incremental parser. This means that it sometimes won't stop as
2299 early as the full parser, for example, it doesn't detect parenthesis
2300 mismatches. The only thing it guarantees is that it starts decoding as
2301 soon as a syntactically valid JSON text has been seen. This means you need
2302 to set resource limits (e.g. C<max_size>) to ensure the parser will stop
2303 parsing in the presence if syntax errors.
2304
2305 The following methods implement this incremental parser.
2306
2307 =head2 incr_parse
2308
2309     $json->incr_parse( [$string] ) # void context
2310     
2311     $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
2312     
2313     @obj_or_empty = $json->incr_parse( [$string] ) # list context
2314
2315 This is the central parsing function. It can both append new text and
2316 extract objects from the stream accumulated so far (both of these
2317 functions are optional).
2318
2319 If C<$string> is given, then this string is appended to the already
2320 existing JSON fragment stored in the C<$json> object.
2321
2322 After that, if the function is called in void context, it will simply
2323 return without doing anything further. This can be used to add more text
2324 in as many chunks as you want.
2325
2326 If the method is called in scalar context, then it will try to extract
2327 exactly I<one> JSON object. If that is successful, it will return this
2328 object, otherwise it will return C<undef>. If there is a parse error,
2329 this method will croak just as C<decode> would do (one can then use
2330 C<incr_skip> to skip the erroneous part). This is the most common way of
2331 using the method.
2332
2333 And finally, in list context, it will try to extract as many objects
2334 from the stream as it can find and return them, or the empty list
2335 otherwise. For this to work, there must be no separators between the JSON
2336 objects or arrays, instead they must be concatenated back-to-back. If
2337 an error occurs, an exception will be raised as in the scalar context
2338 case. Note that in this case, any previously-parsed JSON texts will be
2339 lost.
2340
2341 Example: Parse some JSON arrays/objects in a given string and return them.
2342
2343     my @objs = JSON->new->incr_parse ("[5][7][1,2]");
2344
2345 =head2 incr_text
2346
2347     $lvalue_string = $json->incr_text
2348
2349 This method returns the currently stored JSON fragment as an lvalue, that
2350 is, you can manipulate it. This I<only> works when a preceding call to
2351 C<incr_parse> in I<scalar context> successfully returned an object. Under
2352 all other circumstances you must not call this function (I mean it.
2353 although in simple tests it might actually work, it I<will> fail under
2354 real world conditions). As a special exception, you can also call this
2355 method before having parsed anything.
2356
2357 This function is useful in two cases: a) finding the trailing text after a
2358 JSON object or b) parsing multiple JSON objects separated by non-JSON text
2359 (such as commas).
2360
2361     $json->incr_text =~ s/\s*,\s*//;
2362
2363 In Perl 5.005, C<lvalue> attribute is not available.
2364 You must write codes like the below:
2365
2366     $string = $json->incr_text;
2367     $string =~ s/\s*,\s*//;
2368     $json->incr_text( $string );
2369
2370 =head2 incr_skip
2371
2372     $json->incr_skip
2373
2374 This will reset the state of the incremental parser and will remove the
2375 parsed text from the input buffer. This is useful after C<incr_parse>
2376 died, in which case the input buffer and incremental parser state is left
2377 unchanged, to skip the text parsed so far and to reset the parse state.
2378
2379 =head2 incr_reset
2380
2381     $json->incr_reset
2382
2383 This completely resets the incremental parser, that is, after this call,
2384 it will be as if the parser had never parsed anything.
2385
2386 This is useful if you want to repeatedly parse JSON objects and want to
2387 ignore any trailing data, which means you have to reset the parser after
2388 each successful decode.
2389
2390 See to L<JSON::XS/INCREMENTAL PARSING> for examples.
2391
2392
2393 =head1 JSON::PP OWN METHODS
2394
2395 =head2 allow_singlequote
2396
2397     $json = $json->allow_singlequote([$enable])
2398
2399 If C<$enable> is true (or missing), then C<decode> will accept
2400 JSON strings quoted by single quotations that are invalid JSON
2401 format.
2402
2403     $json->allow_singlequote->decode({"foo":'bar'});
2404     $json->allow_singlequote->decode({'foo':"bar"});
2405     $json->allow_singlequote->decode({'foo':'bar'});
2406
2407 As same as the C<relaxed> option, this option may be used to parse
2408 application-specific files written by humans.
2409
2410
2411 =head2 allow_barekey
2412
2413     $json = $json->allow_barekey([$enable])
2414
2415 If C<$enable> is true (or missing), then C<decode> will accept
2416 bare keys of JSON object that are invalid JSON format.
2417
2418 As same as the C<relaxed> option, this option may be used to parse
2419 application-specific files written by humans.
2420
2421     $json->allow_barekey->decode('{foo:"bar"}');
2422
2423 =head2 allow_bignum
2424
2425     $json = $json->allow_bignum([$enable])
2426
2427 If C<$enable> is true (or missing), then C<decode> will convert
2428 the big integer Perl cannot handle as integer into a L<Math::BigInt>
2429 object and convert a floating number (any) into a L<Math::BigFloat>.
2430
2431 On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
2432 objects into JSON numbers with C<allow_blessed> enable.
2433
2434    $json->allow_nonref->allow_blessed->allow_bignum;
2435    $bigfloat = $json->decode('2.000000000000000000000000001');
2436    print $json->encode($bigfloat);
2437    # => 2.000000000000000000000000001
2438
2439 See to L<JSON::XS/MAPPING> about the normal conversion of JSON number.
2440
2441 =head2 loose
2442
2443     $json = $json->loose([$enable])
2444
2445 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
2446 and the module doesn't allow to C<decode> to these (except for \x2f).
2447 If C<$enable> is true (or missing), then C<decode>  will accept these
2448 unescaped strings.
2449
2450     $json->loose->decode(qq|["abc
2451                                    def"]|);
2452
2453 See L<JSON::XS/SSECURITY CONSIDERATIONS>.
2454
2455 =head2 escape_slash
2456
2457     $json = $json->escape_slash([$enable])
2458
2459 According to JSON Grammar, I<slash> (U+002F) is escaped. But default
2460 JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
2461
2462 If C<$enable> is true (or missing), then C<encode> will escape slashes.
2463
2464 =head2 indent_length
2465
2466     $json = $json->indent_length($length)
2467
2468 JSON::XS indent space length is 3 and cannot be changed.
2469 JSON::PP set the indent space length with the given $length.
2470 The default is 3. The acceptable range is 0 to 15.
2471
2472 =head2 sort_by
2473
2474     $json = $json->sort_by($function_name)
2475     $json = $json->sort_by($subroutine_ref)
2476
2477 If $function_name or $subroutine_ref are set, its sort routine are used
2478 in encoding JSON objects.
2479
2480    $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
2481    # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
2482
2483    $js = $pc->sort_by('own_sort')->encode($obj);
2484    # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
2485
2486    sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
2487
2488 As the sorting routine runs in the JSON::PP scope, the given
2489 subroutine name and the special variables C<$a>, C<$b> will begin
2490 'JSON::PP::'.
2491
2492 If $integer is set, then the effect is same as C<canonical> on.
2493
2494 =head1 INTERNAL
2495
2496 For developers.
2497
2498 =over
2499
2500 =item PP_encode_box
2501
2502 Returns
2503
2504         {
2505             depth        => $depth,
2506             indent_count => $indent_count,
2507         }
2508
2509
2510 =item PP_decode_box
2511
2512 Returns
2513
2514         {
2515             text    => $text,
2516             at      => $at,
2517             ch      => $ch,
2518             len     => $len,
2519             depth   => $depth,
2520             encoding      => $encoding,
2521             is_valid_utf8 => $is_valid_utf8,
2522         };
2523
2524 =back
2525
2526 =head1 MAPPING
2527
2528 This section is copied from JSON::XS and modified to C<JSON::PP>.
2529 JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
2530
2531 See to L<JSON::XS/MAPPING>.
2532
2533 =head2 JSON -> PERL
2534
2535 =over 4
2536
2537 =item object
2538
2539 A JSON object becomes a reference to a hash in Perl. No ordering of object
2540 keys is preserved (JSON does not preserver object key ordering itself).
2541
2542 =item array
2543
2544 A JSON array becomes a reference to an array in Perl.
2545
2546 =item string
2547
2548 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
2549 are represented by the same codepoints in the Perl string, so no manual
2550 decoding is necessary.
2551
2552 =item number
2553
2554 A JSON number becomes either an integer, numeric (floating point) or
2555 string scalar in perl, depending on its range and any fractional parts. On
2556 the Perl level, there is no difference between those as Perl handles all
2557 the conversion details, but an integer may take slightly less memory and
2558 might represent more values exactly than floating point numbers.
2559
2560 If the number consists of digits only, C<JSON> will try to represent
2561 it as an integer value. If that fails, it will try to represent it as
2562 a numeric (floating point) value if that is possible without loss of
2563 precision. Otherwise it will preserve the number as a string value (in
2564 which case you lose roundtripping ability, as the JSON number will be
2565 re-encoded to a JSON string).
2566
2567 Numbers containing a fractional or exponential part will always be
2568 represented as numeric (floating point) values, possibly at a loss of
2569 precision (in which case you might lose perfect roundtripping ability, but
2570 the JSON number will still be re-encoded as a JSON number).
2571
2572 Note that precision is not accuracy - binary floating point values cannot
2573 represent most decimal fractions exactly, and when converting from and to
2574 floating point, C<JSON> only guarantees precision up to but not including
2575 the least significant bit.
2576
2577 When C<allow_bignum> is enable, the big integers 
2578 and the numeric can be optionally converted into L<Math::BigInt> and
2579 L<Math::BigFloat> objects.
2580
2581 =item true, false
2582
2583 These JSON atoms become C<JSON::PP::true> and C<JSON::PP::false>,
2584 respectively. They are overloaded to act almost exactly like the numbers
2585 C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
2586 the C<JSON::is_bool> function.
2587
2588    print JSON::PP::true . "\n";
2589     => true
2590    print JSON::PP::true + 1;
2591     => 1
2592
2593    ok(JSON::true eq  '1');
2594    ok(JSON::true == 1);
2595
2596 C<JSON> will install these missing overloading features to the backend modules.
2597
2598
2599 =item null
2600
2601 A JSON null atom becomes C<undef> in Perl.
2602
2603 C<JSON::PP::null> returns C<undef>.
2604
2605 =back
2606
2607
2608 =head2 PERL -> JSON
2609
2610 The mapping from Perl to JSON is slightly more difficult, as Perl is a
2611 truly typeless language, so we can only guess which JSON type is meant by
2612 a Perl value.
2613
2614 =over 4
2615
2616 =item hash references
2617
2618 Perl hash references become JSON objects. As there is no inherent ordering
2619 in hash keys (or JSON objects), they will usually be encoded in a
2620 pseudo-random order that can change between runs of the same program but
2621 stays generally the same within a single run of a program. C<JSON>
2622 optionally sort the hash keys (determined by the I<canonical> flag), so
2623 the same data structure will serialise to the same JSON text (given same
2624 settings and version of JSON::XS), but this incurs a runtime overhead
2625 and is only rarely useful, e.g. when you want to compare some JSON text
2626 against another for equality.
2627
2628
2629 =item array references
2630
2631 Perl array references become JSON arrays.
2632
2633 =item other references
2634
2635 Other unblessed references are generally not allowed and will cause an
2636 exception to be thrown, except for references to the integers C<0> and
2637 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
2638 also use C<JSON::false> and C<JSON::true> to improve readability.
2639
2640    to_json [\0,JSON::PP::true]      # yields [false,true]
2641
2642 =item JSON::PP::true, JSON::PP::false, JSON::PP::null
2643
2644 These special values become JSON true and JSON false values,
2645 respectively. You can also use C<\1> and C<\0> directly if you want.
2646
2647 JSON::PP::null returns C<undef>.
2648
2649 =item blessed objects
2650
2651 Blessed objects are not directly representable in JSON. See the
2652 C<allow_blessed> and C<convert_blessed> methods on various options on
2653 how to deal with this: basically, you can choose between throwing an
2654 exception, encoding the reference as if it weren't blessed, or provide
2655 your own serialiser method.
2656
2657 See to L<convert_blessed>.
2658
2659 =item simple scalars
2660
2661 Simple Perl scalars (any scalar that is not a reference) are the most
2662 difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
2663 JSON C<null> values, scalars that have last been used in a string context
2664 before encoding as JSON strings, and anything else as number value:
2665
2666    # dump as number
2667    encode_json [2]                      # yields [2]
2668    encode_json [-3.0e17]                # yields [-3e+17]
2669    my $value = 5; encode_json [$value]  # yields [5]
2670
2671    # used as string, so dump as string
2672    print $value;
2673    encode_json [$value]                 # yields ["5"]
2674
2675    # undef becomes null
2676    encode_json [undef]                  # yields [null]
2677
2678 You can force the type to be a string by stringifying it:
2679
2680    my $x = 3.1; # some variable containing a number
2681    "$x";        # stringified
2682    $x .= "";    # another, more awkward way to stringify
2683    print $x;    # perl does it for you, too, quite often
2684
2685 You can force the type to be a number by numifying it:
2686
2687    my $x = "3"; # some variable containing a string
2688    $x += 0;     # numify it, ensuring it will be dumped as a number
2689    $x *= 1;     # same thing, the choice is yours.
2690
2691 You can not currently force the type in other, less obscure, ways.
2692
2693 Note that numerical precision has the same meaning as under Perl (so
2694 binary to decimal conversion follows the same rules as in Perl, which
2695 can differ to other languages). Also, your perl interpreter might expose
2696 extensions to the floating point numbers of your platform, such as
2697 infinities or NaN's - these cannot be represented in JSON, and it is an
2698 error to pass those in.
2699
2700 =item Big Number
2701
2702 When C<allow_bignum> is enable, 
2703 C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
2704 objects into JSON numbers.
2705
2706
2707 =back
2708
2709 =head1 UNICODE HANDLING ON PERLS
2710
2711 If you do not know about Unicode on Perl well,
2712 please check L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
2713
2714 =head2 Perl 5.8 and later
2715
2716 Perl can handle Unicode and the JSON::PP de/encode methods also work properly.
2717
2718     $json->allow_nonref->encode(chr hex 3042);
2719     $json->allow_nonref->encode(chr hex 12345);
2720
2721 Returns C<"\u3042"> and C<"\ud808\udf45"> respectively.
2722
2723     $json->allow_nonref->decode('"\u3042"');
2724     $json->allow_nonref->decode('"\ud808\udf45"');
2725
2726 Returns UTF-8 encoded strings with UTF8 flag, regarded as C<U+3042> and C<U+12345>.
2727
2728 Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in C<join> was broken,
2729 so JSON::PP wraps the C<join> with a subroutine. Thus JSON::PP works slow in the versions.
2730
2731
2732 =head2 Perl 5.6
2733
2734 Perl can handle Unicode and the JSON::PP de/encode methods also work.
2735
2736 =head2 Perl 5.005
2737
2738 Perl 5.005 is a byte semantics world -- all strings are sequences of bytes.
2739 That means the unicode handling is not available.
2740
2741 In encoding,
2742
2743     $json->allow_nonref->encode(chr hex 3042);  # hex 3042 is 12354.
2744     $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
2745
2746 Returns C<B> and C<E>, as C<chr> takes a value more than 255, it treats
2747 as C<$value % 256>, so the above codes are equivalent to :
2748
2749     $json->allow_nonref->encode(chr 66);
2750     $json->allow_nonref->encode(chr 69);
2751
2752 In decoding,
2753
2754     $json->decode('"\u00e3\u0081\u0082"');
2755
2756 The returned is a byte sequence C<0xE3 0x81 0x82> for UTF-8 encoded
2757 japanese character (C<HIRAGANA LETTER A>).
2758 And if it is represented in Unicode code point, C<U+3042>.
2759
2760 Next, 
2761
2762     $json->decode('"\u3042"');
2763
2764 We ordinary expect the returned value is a Unicode character C<U+3042>.
2765 But here is 5.005 world. This is C<0xE3 0x81 0x82>.
2766
2767     $json->decode('"\ud808\udf45"');
2768
2769 This is not a character C<U+12345> but bytes - C<0xf0 0x92 0x8d 0x85>.
2770
2771
2772 =head1 TODO
2773
2774 =over
2775
2776 =item speed
2777
2778 =item memory saving
2779
2780 =back
2781
2782
2783 =head1 SEE ALSO
2784
2785 Most of the document are copied and modified from JSON::XS doc.
2786
2787 L<JSON::XS>
2788
2789 RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>)
2790
2791 =head1 AUTHOR
2792
2793 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
2794
2795
2796 =head1 COPYRIGHT AND LICENSE
2797
2798 Copyright 2007-2012 by Makamaka Hannyaharamitu
2799
2800 This library is free software; you can redistribute it and/or modify
2801 it under the same terms as Perl itself. 
2802
2803 =cut