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