Debian Codegraph @

lib/JSON/backportPP.pm

raw
1 package # This is JSON::backportPP
2 JSON::PP;
3
4 # JSON-2.0
5
6 use 5.005;
7 use strict;
8
9 use Exporter ();
10 BEGIN { @JSON::backportPP::ISA = ('Exporter') }
11
12 use overload ();
13 use JSON::backportPP::Boolean;
14
15 use Carp ();
16 #use Devel::Peek;
17
18 $JSON::backportPP::VERSION = '4.12';
19
20 @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
21
22 # instead of hash-access, i tried index-access for speed.
23 # but this method is not faster than what i expected. so it will be changed.
24
25 use constant P_ASCII => 0;
26 use constant P_LATIN1 => 1;
27 use constant P_UTF8 => 2;
28 use constant P_INDENT => 3;
29 use constant P_CANONICAL => 4;
30 use constant P_SPACE_BEFORE => 5;
31 use constant P_SPACE_AFTER => 6;
32 use constant P_ALLOW_NONREF => 7;
33 use constant P_SHRINK => 8;
34 use constant P_ALLOW_BLESSED => 9;
35 use constant P_CONVERT_BLESSED => 10;
36 use constant P_RELAXED => 11;
37
38 use constant P_LOOSE => 12;
39 use constant P_ALLOW_BIGNUM => 13;
40 use constant P_ALLOW_BAREKEY => 14;
41 use constant P_ALLOW_SINGLEQUOTE => 15;
42 use constant P_ESCAPE_SLASH => 16;
43 use constant P_AS_NONBLESSED => 17;
44
45 use constant P_ALLOW_UNKNOWN => 18;
46 use constant P_ALLOW_TAGS => 19;
47
48 use constant OLD_PERL => $] < 5.008 ? 1 : 0;
49 use constant USE_B => $ENV{PERL_JSON_PP_USE_B} || 0;
50 use constant CORE_BOOL => defined &builtin::is_bool;
51
52 my $invalid_char_re;
53
54 BEGIN {
55 $invalid_char_re = "[";
56 for my $i (0 .. 0x01F, 0x22, 0x5c) { # '/' is ok
57 $invalid_char_re .= quotemeta chr utf8::unicode_to_native($i);
58 }
59
60 $invalid_char_re = qr/$invalid_char_re]/;
61 }
62
63 BEGIN {
64 if (USE_B) {
65 require B;
66 }
67 }
68
69 BEGIN {
70 my @xs_compati_bit_properties = qw(
71 latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
72 allow_blessed convert_blessed relaxed allow_unknown
73 allow_tags
74 );
75 my @pp_bit_properties = qw(
76 allow_singlequote allow_bignum loose
77 allow_barekey escape_slash as_nonblessed
78 );
79
80 # Perl version check, Unicode handling is enabled?
81 # Helper module sets @JSON::PP::_properties.
82 if ( OLD_PERL ) {
83 my $helper = $] >= 5.006 ? 'JSON::backportPP::Compat5006' : 'JSON::backportPP::Compat5005';
84 eval qq| require $helper |;
85 if ($@) { Carp::croak $@; }
86 }
87
88 for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
89 my $property_id = 'P_' . uc($name);
90
91 eval qq/
92 sub $name {
93 my \$enable = defined \$_[1] ? \$_[1] : 1;
94
95 if (\$enable) {
96 \$_[0]->{PROPS}->[$property_id] = 1;
97 }
98 else {
99 \$_[0]->{PROPS}->[$property_id] = 0;
100 }
101
102 \$_[0];
103 }
104
105 sub get_$name {
106 \$_[0]->{PROPS}->[$property_id] ? 1 : '';
107 }
108 /;
109 }
110
111 }
112
113
114
115 # Functions
116
117 my $JSON; # cache
118
119 sub encode_json ($) { # encode
120 ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
121 }
122
123
124 sub decode_json { # decode
125 ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
126 }
127
128 # Obsoleted
129
130 sub to_json($) {
131 Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
132 }
133
134
135 sub from_json($) {
136 Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
137 }
138
139
140 # Methods
141
142 sub new {
143 my $class = shift;
144 my $self = {
145 max_depth => 512,
146 max_size => 0,
147 indent_length => 3,
148 };
149
150 $self->{PROPS}[P_ALLOW_NONREF] = 1;
151
152 bless $self, $class;
153 }
154
155
156 sub encode {
157 return $_[0]->PP_encode_json($_[1]);
158 }
159
160
161 sub decode {
162 return $_[0]->PP_decode_json($_[1], 0x00000000);
163 }
164
165
166 sub decode_prefix {
167 return $_[0]->PP_decode_json($_[1], 0x00000001);
168 }
169
170
171 # accessor
172
173
174 # pretty printing
175
176 sub pretty {
177 my ($self, $v) = @_;
178 my $enable = defined $v ? $v : 1;
179
180 if ($enable) { # indent_length(3) for JSON::XS compatibility
181 $self->indent(1)->space_before(1)->space_after(1);
182 }
183 else {
184 $self->indent(0)->space_before(0)->space_after(0);
185 }
186
187 $self;
188 }
189
190 # etc
191
192 sub max_depth {
193 my $max = defined $_[1] ? $_[1] : 0x80000000;
194 $_[0]->{max_depth} = $max;
195 $_[0];
196 }
197
198
199 sub get_max_depth { $_[0]->{max_depth}; }
200
201
202 sub max_size {
203 my $max = defined $_[1] ? $_[1] : 0;
204 $_[0]->{max_size} = $max;
205 $_[0];
206 }
207
208
209 sub get_max_size { $_[0]->{max_size}; }
210
211 sub boolean_values {
212 my $self = shift;
213 if (@_) {
214 my ($false, $true) = @_;
215 $self->{false} = $false;
216 $self->{true} = $true;
217 if (CORE_BOOL) {
218 BEGIN { CORE_BOOL and warnings->unimport(qw(experimental::builtin)) }
219 if (builtin::is_bool($true) && builtin::is_bool($false) && $true && !$false) {
220 $self->{core_bools} = !!1;
221 }
222 else {
223 delete $self->{core_bools};
224 }
225 }
226 } else {
227 delete $self->{false};
228 delete $self->{true};
229 delete $self->{core_bools};
230 }
231 return $self;
232 }
233
234 sub core_bools {
235 my $self = shift;
236 my $core_bools = defined $_[0] ? $_[0] : 1;
237 if ($core_bools) {
238 $self->{true} = !!1;
239 $self->{false} = !!0;
240 $self->{core_bools} = !!1;
241 }
242 else {
243 $self->{true} = $JSON::PP::true;
244 $self->{false} = $JSON::PP::false;
245 $self->{core_bools} = !!0;
246 }
247 return $self;
248 }
249
250 sub get_core_bools {
251 my $self = shift;
252 return !!$self->{core_bools};
253 }
254
255 sub unblessed_bool {
256 my $self = shift;
257 return $self->core_bools(@_);
258 }
259
260 sub get_unblessed_bool {
261 my $self = shift;
262 return $self->get_core_bools(@_);
263 }
264
265 sub get_boolean_values {
266 my $self = shift;
267 if (exists $self->{true} and exists $self->{false}) {
268 return @$self{qw/false true/};
269 }
270 return;
271 }
272
273 sub filter_json_object {
274 if (defined $_[1] and ref $_[1] eq 'CODE') {
275 $_[0]->{cb_object} = $_[1];
276 } else {
277 delete $_[0]->{cb_object};
278 }
279 $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
280 $_[0];
281 }
282
283 sub filter_json_single_key_object {
284 if (@_ == 1 or @_ > 3) {
285 Carp::croak("Usage: JSON::PP::filter_json_single_key_object(self, key, callback = undef)");
286 }
287 if (defined $_[2] and ref $_[2] eq 'CODE') {
288 $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
289 } else {
290 delete $_[0]->{cb_sk_object}->{$_[1]};
291 delete $_[0]->{cb_sk_object} unless %{$_[0]->{cb_sk_object} || {}};
292 }
293 $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
294 $_[0];
295 }
296
297 sub indent_length {
298 if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
299 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
300 }
301 else {
302 $_[0]->{indent_length} = $_[1];
303 }
304 $_[0];
305 }
306
307 sub get_indent_length {
308 $_[0]->{indent_length};
309 }
310
311 sub sort_by {
312 $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
313 $_[0];
314 }
315
316 sub allow_bigint {
317 Carp::carp("allow_bigint() is obsoleted. use allow_bignum() instead.");
318 $_[0]->allow_bignum;
319 }
320
321 ###############################
322
323 ###
324 ### Perl => JSON
325 ###
326
327
328 { # Convert
329
330 my $max_depth;
331 my $indent;
332 my $ascii;
333 my $latin1;
334 my $utf8;
335 my $space_before;
336 my $space_after;
337 my $canonical;
338 my $allow_blessed;
339 my $convert_blessed;
340
341 my $indent_length;
342 my $escape_slash;
343 my $bignum;
344 my $as_nonblessed;
345 my $allow_tags;
346
347 my $depth;
348 my $indent_count;
349 my $keysort;
350
351
352 sub PP_encode_json {
353 my $self = shift;
354 my $obj = shift;
355
356 $indent_count = 0;
357 $depth = 0;
358
359 my $props = $self->{PROPS};
360
361 ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
362 $convert_blessed, $escape_slash, $bignum, $as_nonblessed, $allow_tags)
363 = @{$props}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
364 P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED, P_ALLOW_TAGS];
365
366 ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
367
368 $keysort = $canonical ? sub { $a cmp $b } : undef;
369
370 if ($self->{sort_by}) {
371 $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
372 : $self->{sort_by} =~ /\D+/ ? $self->{sort_by}
373 : sub { $a cmp $b };
374 }
375
376 encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
377 if(!ref $obj and !$props->[ P_ALLOW_NONREF ]);
378
379 my $str = $self->object_to_json($obj);
380
381 $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
382
383 return $str;
384 }
385
386
387 sub object_to_json {
388 my ($self, $obj) = @_;
389 my $type = ref($obj);
390
391 if($type eq 'HASH'){
392 return $self->hash_to_json($obj);
393 }
394 elsif($type eq 'ARRAY'){
395 return $self->array_to_json($obj);
396 }
397 elsif ($type) { # blessed object?
398 if (blessed($obj)) {
399
400 return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
401
402 if ( $allow_tags and $obj->can('FREEZE') ) {
403 my $obj_class = ref $obj || $obj;
404 $obj = bless $obj, $obj_class;
405 my @results = $obj->FREEZE('JSON');
406 if ( @results and ref $results[0] ) {
407 if ( refaddr( $obj ) eq refaddr( $results[0] ) ) {
408 encode_error( sprintf(
409 "%s::FREEZE method returned same object as was passed instead of a new one",
410 ref $obj
411 ) );
412 }
413 }
414 return '("'.$obj_class.'")['.join(',', @results).']';
415 }
416
417 if ( $convert_blessed and $obj->can('TO_JSON') ) {
418 my $result = $obj->TO_JSON();
419 if ( defined $result and ref( $result ) ) {
420 if ( refaddr( $obj ) eq refaddr( $result ) ) {
421 encode_error( sprintf(
422 "%s::TO_JSON method returned same object as was passed instead of a new one",
423 ref $obj
424 ) );
425 }
426 }
427
428 return $self->object_to_json( $result );
429 }
430
431 return "$obj" if ( $bignum and _is_bignum($obj) );
432
433 if ($allow_blessed) {
434 return $self->blessed_to_json($obj) if ($as_nonblessed); # will be removed.
435 return 'null';
436 }
437 encode_error( sprintf("encountered object '%s', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)", $obj)
438 );
439 }
440 else {
441 return $self->value_to_json($obj);
442 }
443 }
444 else{
445 return $self->value_to_json($obj);
446 }
447 }
448
449
450 sub hash_to_json {
451 my ($self, $obj) = @_;
452 my @res;
453
454 encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
455 if (++$depth > $max_depth);
456
457 my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
458 my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : '');
459
460 for my $k ( _sort( $obj ) ) {
461 if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized
462 push @res, $self->string_to_json( $k )
463 . $del
464 . ( ref $obj->{$k} ? $self->object_to_json( $obj->{$k} ) : $self->value_to_json( $obj->{$k} ) );
465 }
466
467 --$depth;
468 $self->_down_indent() if ($indent);
469
470 return '{}' unless @res;
471 return '{' . $pre . join( ",$pre", @res ) . $post . '}';
472 }
473
474
475 sub array_to_json {
476 my ($self, $obj) = @_;
477 my @res;
478
479 encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
480 if (++$depth > $max_depth);
481
482 my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
483
484 for my $v (@$obj){
485 push @res, ref($v) ? $self->object_to_json($v) : $self->value_to_json($v);
486 }
487
488 --$depth;
489 $self->_down_indent() if ($indent);
490
491 return '[]' unless @res;
492 return '[' . $pre . join( ",$pre", @res ) . $post . ']';
493 }
494
495 sub _looks_like_number {
496 my $value = shift;
497 if (USE_B) {
498 my $b_obj = B::svref_2object(\$value);
499 my $flags = $b_obj->FLAGS;
500 return 1 if $flags & ( B::SVp_IOK() | B::SVp_NOK() ) and !( $flags & B::SVp_POK() );
501 return;
502 } else {
503 no warnings 'numeric';
504 # if the utf8 flag is on, it almost certainly started as a string
505 return if utf8::is_utf8($value);
506 # detect numbers
507 # string & "" -> ""
508 # number & "" -> 0 (with warning)
509 # nan and inf can detect as numbers, so check with * 0
510 return unless length((my $dummy = "") & $value);
511 return unless 0 + $value eq $value;
512 return 1 if $value * 0 == 0;
513 return -1; # inf/nan
514 }
515 }
516
517 sub value_to_json {
518 my ($self, $value) = @_;
519
520 return 'null' if(!defined $value);
521
522 my $type = ref($value);
523
524 if (!$type) {
525 BEGIN { CORE_BOOL and warnings->unimport('experimental::builtin') }
526 if (CORE_BOOL && builtin::is_bool($value)) {
527 return $value ? 'true' : 'false';
528 }
529 elsif (_looks_like_number($value)) {
530 return $value;
531 }
532 return $self->string_to_json($value);
533 }
534 elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ){
535 return $$value == 1 ? 'true' : 'false';
536 }
537 else {
538 if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
539 return $self->value_to_json("$value");
540 }
541
542 if ($type eq 'SCALAR' and defined $$value) {
543 return $$value eq '1' ? 'true'
544 : $$value eq '0' ? 'false'
545 : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
546 : encode_error("cannot encode reference to scalar");
547 }
548
549 if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
550 return 'null';
551 }
552 else {
553 if ( $type eq 'SCALAR' or $type eq 'REF' ) {
554 encode_error("cannot encode reference to scalar");
555 }
556 else {
557 encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
558 }
559 }
560
561 }
562 }
563
564
565 my %esc = (
566 "\n" => '\n',
567 "\r" => '\r',
568 "\t" => '\t',
569 "\f" => '\f',
570 "\b" => '\b',
571 "\"" => '\"',
572 "\\" => '\\\\',
573 "\'" => '\\\'',
574 );
575
576
577 sub string_to_json {
578 my ($self, $arg) = @_;
579
580 $arg =~ s/(["\\\n\r\t\f\b])/$esc{$1}/g;
581 $arg =~ s/\//\\\//g if ($escape_slash);
582
583 # On ASCII platforms, matches [\x00-\x08\x0b\x0e-\x1f]
584 $arg =~ s/([^\n\t\c?[:^cntrl:][:^ascii:]])/'\\u00' . unpack('H2', $1)/eg;
585
586 if ($ascii) {
587 $arg = JSON_PP_encode_ascii($arg);
588 }
589
590 if ($latin1) {
591 $arg = JSON_PP_encode_latin1($arg);
592 }
593
594 if ($utf8) {
595 utf8::encode($arg);
596 }
597
598 return '"' . $arg . '"';
599 }
600
601
602 sub blessed_to_json {
603 my $reftype = reftype($_[1]) || '';
604 if ($reftype eq 'HASH') {
605 return $_[0]->hash_to_json($_[1]);
606 }
607 elsif ($reftype eq 'ARRAY') {
608 return $_[0]->array_to_json($_[1]);
609 }
610 else {
611 return 'null';
612 }
613 }
614
615
616 sub encode_error {
617 my $error = shift;
618 Carp::croak "$error";
619 }
620
621
622 sub _sort {
623 defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]};
624 }
625
626
627 sub _up_indent {
628 my $self = shift;
629 my $space = ' ' x $indent_length;
630
631 my ($pre,$post) = ('','');
632
633 $post = "\n" . $space x $indent_count;
634
635 $indent_count++;
636
637 $pre = "\n" . $space x $indent_count;
638
639 return ($pre,$post);
640 }
641
642
643 sub _down_indent { $indent_count--; }
644
645
646 sub PP_encode_box {
647 {
648 depth => $depth,
649 indent_count => $indent_count,
650 };
651 }
652
653 } # Convert
654
655
656 sub _encode_ascii {
657 join('',
658 map {
659 chr($_) =~ /[[:ascii:]]/ ?
660 chr($_) :
661 $_ <= 65535 ?
662 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
663 } unpack('U*', $_[0])
664 );
665 }
666
667
668 sub _encode_latin1 {
669 join('',
670 map {
671 $_ <= 255 ?
672 chr($_) :
673 $_ <= 65535 ?
674 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
675 } unpack('U*', $_[0])
676 );
677 }
678
679
680 sub _encode_surrogates { # from perlunicode
681 my $uni = $_[0] - 0x10000;
682 return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
683 }
684
685
686 sub _is_bignum {
687 $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
688 }
689
690
691
692 #
693 # JSON => Perl
694 #
695
696 my $max_intsize;
697
698 BEGIN {
699 my $checkint = 1111;
700 for my $d (5..64) {
701 $checkint .= 1;
702 my $int = eval qq| $checkint |;
703 if ($int =~ /[eE]/) {
704 $max_intsize = $d - 1;
705 last;
706 }
707 }
708 }
709
710 { # PARSE
711
712 my %escapes = ( # by Jeremy Muhlich <jmuhlich [at] bitflood.org>
713 b => "\b",
714 t => "\t",
715 n => "\n",
716 f => "\f",
717 r => "\r",
718 '\\' => '\\',
719 '"' => '"',
720 '/' => '/',
721 );
722
723 my $text; # json data
724 my $at; # offset
725 my $ch; # first character
726 my $len; # text length (changed according to UTF8 or NON UTF8)
727 # INTERNAL
728 my $depth; # nest counter
729 my $encoding; # json text encoding
730 my $is_valid_utf8; # temp variable
731 my $utf8_len; # utf8 byte length
732 # FLAGS
733 my $utf8; # must be utf8
734 my $max_depth; # max nest number of objects and arrays
735 my $max_size;
736 my $relaxed;
737 my $cb_object;
738 my $cb_sk_object;
739
740 my $F_HOOK;
741
742 my $allow_bignum; # using Math::BigInt/BigFloat
743 my $singlequote; # loosely quoting
744 my $loose; #
745 my $allow_barekey; # bareKey
746 my $allow_tags;
747
748 my $alt_true;
749 my $alt_false;
750
751 sub _detect_utf_encoding {
752 my $text = shift;
753 my @octets = unpack('C4', $text);
754 return 'unknown' unless defined $octets[3];
755 return ( $octets[0] and $octets[1]) ? 'UTF-8'
756 : (!$octets[0] and $octets[1]) ? 'UTF-16BE'
757 : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
758 : ( $octets[2] ) ? 'UTF-16LE'
759 : (!$octets[2] ) ? 'UTF-32LE'
760 : 'unknown';
761 }
762
763 sub PP_decode_json {
764 my ($self, $want_offset);
765
766 ($self, $text, $want_offset) = @_;
767
768 ($at, $ch, $depth) = (0, '', 0);
769
770 if ( !defined $text or ref $text ) {
771 decode_error("malformed JSON string, neither array, object, number, string or atom");
772 }
773
774 my $props = $self->{PROPS};
775
776 ($utf8, $relaxed, $loose, $allow_bignum, $allow_barekey, $singlequote, $allow_tags)
777 = @{$props}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE, P_ALLOW_TAGS];
778
779 ($alt_true, $alt_false) = @$self{qw/true false/};
780
781 if ( $utf8 ) {
782 $encoding = _detect_utf_encoding($text);
783 if ($encoding ne 'UTF-8' and $encoding ne 'unknown') {
784 require Encode;
785 Encode::from_to($text, $encoding, 'utf-8');
786 } else {
787 utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
788 }
789 }
790 else {
791 utf8::encode( $text );
792 }
793
794 $len = length $text;
795
796 ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
797 = @{$self}{qw/max_depth max_size cb_object cb_sk_object F_HOOK/};
798
799 if ($max_size > 1) {
800 use bytes;
801 my $bytes = length $text;
802 decode_error(
803 sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
804 , $bytes, $max_size), 1
805 ) if ($bytes > $max_size);
806 }
807
808 white(); # remove head white space
809
810 decode_error("malformed JSON string, neither array, object, number, string or atom") unless defined $ch; # Is there a first character for JSON structure?
811
812 my $result = value();
813
814 if ( !$props->[ P_ALLOW_NONREF ] and !ref $result ) {
815 decode_error(
816 'JSON text must be an object or array (but found number, string, true, false or null,'
817 . ' use allow_nonref to allow this)', 1);
818 }
819
820 Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
821
822 my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
823
824 white(); # remove tail white space
825
826 return ( $result, $consumed ) if $want_offset; # all right if decode_prefix
827
828 decode_error("garbage after JSON object") if defined $ch;
829
830 $result;
831 }
832
833
834 sub next_chr {
835 return $ch = undef if($at >= $len);
836 $ch = substr($text, $at++, 1);
837 }
838
839
840 sub value {
841 white();
842 return if(!defined $ch);
843 return object() if($ch eq '{');
844 return array() if($ch eq '[');
845 return tag() if($ch eq '(');
846 return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
847 return number() if($ch =~ /[0-9]/ or $ch eq '-');
848 return word();
849 }
850
851 sub string {
852 my $utf16;
853 my $is_utf8;
854
855 ($is_valid_utf8, $utf8_len) = ('', 0);
856
857 my $s = ''; # basically UTF8 flag on
858
859 if($ch eq '"' or ($singlequote and $ch eq "'")){
860 my $boundChar = $ch;
861
862 OUTER: while( defined(next_chr()) ){
863
864 if($ch eq $boundChar){
865 next_chr();
866
867 if ($utf16) {
868 decode_error("missing low surrogate character in surrogate pair");
869 }
870
871 utf8::decode($s) if($is_utf8);
872
873 return $s;
874 }
875 elsif($ch eq '\\'){
876 next_chr();
877 if(exists $escapes{$ch}){
878 $s .= $escapes{$ch};
879 }
880 elsif($ch eq 'u'){ # UNICODE handling
881 my $u = '';
882
883 for(1..4){
884 $ch = next_chr();
885 last OUTER if($ch !~ /[0-9a-fA-F]/);
886 $u .= $ch;
887 }
888
889 # U+D800 - U+DBFF
890 if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
891 $utf16 = $u;
892 }
893 # U+DC00 - U+DFFF
894 elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
895 unless (defined $utf16) {
896 decode_error("missing high surrogate character in surrogate pair");
897 }
898 $is_utf8 = 1;
899 $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
900 $utf16 = undef;
901 }
902 else {
903 if (defined $utf16) {
904 decode_error("surrogate pair expected");
905 }
906
907 my $hex = hex( $u );
908 if ( chr $u =~ /[[:^ascii:]]/ ) {
909 $is_utf8 = 1;
910 $s .= JSON_PP_decode_unicode($u) || next;
911 }
912 else {
913 $s .= chr $hex;
914 }
915 }
916
917 }
918 else{
919 unless ($loose) {
920 $at -= 2;
921 decode_error('illegal backslash escape sequence in string');
922 }
923 $s .= $ch;
924 }
925 }
926 else{
927
928 if ( $ch =~ /[[:^ascii:]]/ ) {
929 unless( $ch = is_valid_utf8($ch) ) {
930 $at -= 1;
931 decode_error("malformed UTF-8 character in JSON string");
932 }
933 else {
934 $at += $utf8_len - 1;
935 }
936
937 $is_utf8 = 1;
938 }
939
940 if (!$loose) {
941 if ($ch =~ $invalid_char_re) { # '/' ok
942 if (!$relaxed or $ch ne "\t") {
943 $at--;
944 decode_error(sprintf "invalid character 0x%X"
945 . " encountered while parsing JSON string",
946 ord $ch);
947 }
948 }
949 }
950
951 $s .= $ch;
952 }
953 }
954 }
955
956 decode_error("unexpected end of string while parsing JSON string");
957 }
958
959
960 sub white {
961 while( defined $ch ){
962 if($ch eq '' or $ch =~ /\A[ \t\r\n]\z/){
963 next_chr();
964 }
965 elsif($relaxed and $ch eq '/'){
966 next_chr();
967 if(defined $ch and $ch eq '/'){
968 1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
969 }
970 elsif(defined $ch and $ch eq '*'){
971 next_chr();
972 while(1){
973 if(defined $ch){
974 if($ch eq '*'){
975 if(defined(next_chr()) and $ch eq '/'){
976 next_chr();
977 last;
978 }
979 }
980 else{
981 next_chr();
982 }
983 }
984 else{
985 decode_error("Unterminated comment");
986 }
987 }
988 next;
989 }
990 else{
991 $at--;
992 decode_error("malformed JSON string, neither array, object, number, string or atom");
993 }
994 }
995 else{
996 if ($relaxed and $ch eq '#') { # correctly?
997 pos($text) = $at;
998 $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
999 $at = pos($text);
1000 next_chr;
1001 next;
1002 }
1003
1004 last;
1005 }
1006 }
1007 }
1008
1009
1010 sub array {
1011 my $a = $_[0] || []; # you can use this code to use another array ref object.
1012
1013 decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
1014 if (++$depth > $max_depth);
1015
1016 next_chr();
1017 white();
1018
1019 if(defined $ch and $ch eq ']'){
1020 --$depth;
1021 next_chr();
1022 return $a;
1023 }
1024 else {
1025 while(defined($ch)){
1026 push @$a, value();
1027
1028 white();
1029
1030 if (!defined $ch) {
1031 last;
1032 }
1033
1034 if($ch eq ']'){
1035 --$depth;
1036 next_chr();
1037 return $a;
1038 }
1039
1040 if($ch ne ','){
1041 last;
1042 }
1043
1044 next_chr();
1045 white();
1046
1047 if ($relaxed and $ch eq ']') {
1048 --$depth;
1049 next_chr();
1050 return $a;
1051 }
1052
1053 }
1054 }
1055
1056 $at-- if defined $ch and $ch ne '';
1057 decode_error(", or ] expected while parsing array");
1058 }
1059
1060 sub tag {
1061 decode_error('malformed JSON string, neither array, object, number, string or atom') unless $allow_tags;
1062
1063 next_chr();
1064 white();
1065
1066 my $tag = value();
1067 return unless defined $tag;
1068 decode_error('malformed JSON string, (tag) must be a string') if ref $tag;
1069
1070 white();
1071
1072 if (!defined $ch or $ch ne ')') {
1073 decode_error(') expected after tag');
1074 }
1075
1076 next_chr();
1077 white();
1078
1079 my $val = value();
1080 return unless defined $val;
1081 decode_error('malformed JSON string, tag value must be an array') unless ref $val eq 'ARRAY';
1082
1083 if (!eval { $tag->can('THAW') }) {
1084 decode_error('cannot decode perl-object (package does not exist)') if $@;
1085 decode_error('cannot decode perl-object (package does not have a THAW method)');
1086 }
1087 $tag->THAW('JSON', @$val);
1088 }
1089
1090 sub object {
1091 my $o = $_[0] || {}; # you can use this code to use another hash ref object.
1092 my $k;
1093
1094 decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
1095 if (++$depth > $max_depth);
1096 next_chr();
1097 white();
1098
1099 if(defined $ch and $ch eq '}'){
1100 --$depth;
1101 next_chr();
1102 if ($F_HOOK) {
1103 return _json_object_hook($o);
1104 }
1105 return $o;
1106 }
1107 else {
1108 while (defined $ch) {
1109 $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
1110 white();
1111
1112 if(!defined $ch or $ch ne ':'){
1113 $at--;
1114 decode_error("':' expected");
1115 }
1116
1117 next_chr();
1118 $o->{$k} = value();
1119 white();
1120
1121 last if (!defined $ch);
1122
1123 if($ch eq '}'){
1124 --$depth;
1125 next_chr();
1126 if ($F_HOOK) {
1127 return _json_object_hook($o);
1128 }
1129 return $o;
1130 }
1131
1132 if($ch ne ','){
1133 last;
1134 }
1135
1136 next_chr();
1137 white();
1138
1139 if ($relaxed and $ch eq '}') {
1140 --$depth;
1141 next_chr();
1142 if ($F_HOOK) {
1143 return _json_object_hook($o);
1144 }
1145 return $o;
1146 }
1147
1148 }
1149
1150 }
1151
1152 $at-- if defined $ch and $ch ne '';
1153 decode_error(", or } expected while parsing object/hash");
1154 }
1155
1156
1157 sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
1158 my $key;
1159 while($ch =~ /[\$\w[:^ascii:]]/){
1160 $key .= $ch;
1161 next_chr();
1162 }
1163 return $key;
1164 }
1165
1166
1167 sub word {
1168 my $word = substr($text,$at-1,4);
1169
1170 if($word eq 'true'){
1171 $at += 3;
1172 next_chr;
1173 return defined $alt_true ? $alt_true : $JSON::PP::true;
1174 }
1175 elsif($word eq 'null'){
1176 $at += 3;
1177 next_chr;
1178 return undef;
1179 }
1180 elsif($word eq 'fals'){
1181 $at += 3;
1182 if(substr($text,$at,1) eq 'e'){
1183 $at++;
1184 next_chr;
1185 return defined $alt_false ? $alt_false : $JSON::PP::false;
1186 }
1187 }
1188
1189 $at--; # for decode_error report
1190
1191 decode_error("'null' expected") if ($word =~ /^n/);
1192 decode_error("'true' expected") if ($word =~ /^t/);
1193 decode_error("'false' expected") if ($word =~ /^f/);
1194 decode_error("malformed JSON string, neither array, object, number, string or atom");
1195 }
1196
1197
1198 sub number {
1199 my $n = '';
1200 my $v;
1201 my $is_dec;
1202 my $is_exp;
1203
1204 if($ch eq '-'){
1205 $n = '-';
1206 next_chr;
1207 if (!defined $ch or $ch !~ /\d/) {
1208 decode_error("malformed number (no digits after initial minus)");
1209 }
1210 }
1211
1212 # According to RFC4627, hex or oct digits are invalid.
1213 if($ch eq '0'){
1214 my $peek = substr($text,$at,1);
1215 if($peek =~ /^[0-9a-dfA-DF]/){ # e may be valid (exponential)
1216 decode_error("malformed number (leading zero must not be followed by another digit)");
1217 }
1218 $n .= $ch;
1219 next_chr;
1220 }
1221
1222 while(defined $ch and $ch =~ /\d/){
1223 $n .= $ch;
1224 next_chr;
1225 }
1226
1227 if(defined $ch and $ch eq '.'){
1228 $n .= '.';
1229 $is_dec = 1;
1230
1231 next_chr;
1232 if (!defined $ch or $ch !~ /\d/) {
1233 decode_error("malformed number (no digits after decimal point)");
1234 }
1235 else {
1236 $n .= $ch;
1237 }
1238
1239 while(defined(next_chr) and $ch =~ /\d/){
1240 $n .= $ch;
1241 }
1242 }
1243
1244 if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
1245 $n .= $ch;
1246 $is_exp = 1;
1247 next_chr;
1248
1249 if(defined($ch) and ($ch eq '+' or $ch eq '-')){
1250 $n .= $ch;
1251 next_chr;
1252 if (!defined $ch or $ch =~ /\D/) {
1253 decode_error("malformed number (no digits after exp sign)");
1254 }
1255 $n .= $ch;
1256 }
1257 elsif(defined($ch) and $ch =~ /\d/){
1258 $n .= $ch;
1259 }
1260 else {
1261 decode_error("malformed number (no digits after exp sign)");
1262 }
1263
1264 while(defined(next_chr) and $ch =~ /\d/){
1265 $n .= $ch;
1266 }
1267
1268 }
1269
1270 $v .= $n;
1271
1272 if ($is_dec or $is_exp) {
1273 if ($allow_bignum) {
1274 require Math::BigFloat;
1275 return Math::BigFloat->new($v);
1276 }
1277 } else {
1278 if (length $v > $max_intsize) {
1279 if ($allow_bignum) { # from Adam Sussman
1280 require Math::BigInt;
1281 return Math::BigInt->new($v);
1282 }
1283 else {
1284 return "$v";
1285 }
1286 }
1287 }
1288
1289 return $is_dec ? $v/1.0 : 0+$v;
1290 }
1291
1292 # Compute how many bytes are in the longest legal official Unicode
1293 # character
1294 my $max_unicode_length = do {
1295 BEGIN { $] >= 5.006 and require warnings and warnings->unimport('utf8') }
1296 chr 0x10FFFF;
1297 };
1298 utf8::encode($max_unicode_length);
1299 $max_unicode_length = length $max_unicode_length;
1300
1301 sub is_valid_utf8 {
1302
1303 # Returns undef (setting $utf8_len to 0) unless the next bytes in $text
1304 # comprise a well-formed UTF-8 encoded character, in which case,
1305 # return those bytes, setting $utf8_len to their count.
1306
1307 my $start_point = substr($text, $at - 1);
1308
1309 # Look no further than the maximum number of bytes in a single
1310 # character
1311 my $limit = $max_unicode_length;
1312 $limit = length($start_point) if $limit > length($start_point);
1313
1314 # Find the number of bytes comprising the first character in $text
1315 # (without having to know the details of its internal representation).
1316 # This loop will iterate just once on well-formed input.
1317 while ($limit > 0) { # Until we succeed or exhaust the input
1318 my $copy = substr($start_point, 0, $limit);
1319
1320 # decode() will return true if all bytes are valid; false
1321 # if any aren't.
1322 if (utf8::decode($copy)) {
1323
1324 # Is valid: get the first character, convert back to bytes,
1325 # and return those bytes.
1326 $copy = substr($copy, 0, 1);
1327 utf8::encode($copy);
1328 $utf8_len = length $copy;
1329 return substr($start_point, 0, $utf8_len);
1330 }
1331
1332 # If it didn't work, it could be that there is a full legal character
1333 # followed by a partial or malformed one. Narrow the window and
1334 # try again.
1335 $limit--;
1336 }
1337
1338 # Failed to find a legal UTF-8 character.
1339 $utf8_len = 0;
1340 return;
1341 }
1342
1343
1344 sub decode_error {
1345 my $error = shift;
1346 my $no_rep = shift;
1347 my $str = defined $text ? substr($text, $at) : '';
1348 my $mess = '';
1349 my $type = 'U*';
1350
1351 if ( OLD_PERL ) {
1352 my $type = $] < 5.006 ? 'C*'
1353 : utf8::is_utf8( $str ) ? 'U*' # 5.6
1354 : 'C*'
1355 ;
1356 }
1357
1358 for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
1359 my $chr_c = chr($c);
1360 $mess .= $chr_c eq '\\' ? '\\\\'
1361 : $chr_c =~ /[[:print:]]/ ? $chr_c
1362 : $chr_c eq '\a' ? '\a'
1363 : $chr_c eq '\t' ? '\t'
1364 : $chr_c eq '\n' ? '\n'
1365 : $chr_c eq '\r' ? '\r'
1366 : $chr_c eq '\f' ? '\f'
1367 : sprintf('\x{%x}', $c)
1368 ;
1369 if ( length $mess >= 20 ) {
1370 $mess .= '...';
1371 last;
1372 }
1373 }
1374
1375 unless ( length $mess ) {
1376 $mess = '(end of string)';
1377 }
1378
1379 Carp::croak (
1380 $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
1381 );
1382
1383 }
1384
1385
1386 sub _json_object_hook {
1387 my $o = $_[0];
1388 my @ks = keys %{$o};
1389
1390 if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
1391 my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
1392 if (@val == 0) {
1393 return $o;
1394 }
1395 elsif (@val == 1) {
1396 return $val[0];
1397 }
1398 else {
1399 Carp::croak("filter_json_single_key_object callbacks must not return more than one scalar");
1400 }
1401 }
1402
1403 my @val = $cb_object->($o) if ($cb_object);
1404 if (@val == 0) {
1405 return $o;
1406 }
1407 elsif (@val == 1) {
1408 return $val[0];
1409 }
1410 else {
1411 Carp::croak("filter_json_object callbacks must not return more than one scalar");
1412 }
1413 }
1414
1415
1416 sub PP_decode_box {
1417 {
1418 text => $text,
1419 at => $at,
1420 ch => $ch,
1421 len => $len,
1422 depth => $depth,
1423 encoding => $encoding,
1424 is_valid_utf8 => $is_valid_utf8,
1425 };
1426 }
1427
1428 } # PARSE
1429
1430
1431 sub _decode_surrogates { # from perlunicode
1432 my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
1433 my $un = pack('U*', $uni);
1434 utf8::encode( $un );
1435 return $un;
1436 }
1437
1438
1439 sub _decode_unicode {
1440 my $un = pack('U', hex shift);
1441 utf8::encode( $un );
1442 return $un;
1443 }
1444
1445 #
1446 # Setup for various Perl versions (the code from JSON::PP58)
1447 #
1448
1449 BEGIN {
1450
1451 unless ( defined &utf8::is_utf8 ) {
1452 require Encode;
1453 *utf8::is_utf8 = *Encode::is_utf8;
1454 }
1455
1456 if ( !OLD_PERL ) {
1457 *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii;
1458 *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1;
1459 *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
1460 *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode;
1461
1462 if ($] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken.
1463 package # hide from PAUSE
1464 JSON::PP;
1465 require subs;
1466 subs->import('join');
1467 eval q|
1468 sub join {
1469 return '' if (@_ < 2);
1470 my $j = shift;
1471 my $str = shift;
1472 for (@_) { $str .= $j . $_; }
1473 return $str;
1474 }
1475 |;
1476 }
1477 }
1478
1479
1480 sub JSON::PP::incr_parse {
1481 local $Carp::CarpLevel = 1;
1482 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ );
1483 }
1484
1485
1486 sub JSON::PP::incr_skip {
1487 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip;
1488 }
1489
1490
1491 sub JSON::PP::incr_reset {
1492 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset;
1493 }
1494
1495 eval q{
1496 sub JSON::PP::incr_text : lvalue {
1497 $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
1498
1499 if ( $_[0]->{_incr_parser}->{incr_pos} ) {
1500 Carp::croak("incr_text cannot be called when the incremental parser already started parsing");
1501 }
1502 $_[0]->{_incr_parser}->{incr_text};
1503 }
1504 } if ( $] >= 5.006 );
1505
1506 } # Setup for various Perl versions (the code from JSON::PP58)
1507
1508
1509 ###############################
1510 # Utilities
1511 #
1512
1513 BEGIN {
1514 eval 'require Scalar::Util';
1515 unless($@){
1516 *JSON::PP::blessed = \&Scalar::Util::blessed;
1517 *JSON::PP::reftype = \&Scalar::Util::reftype;
1518 *JSON::PP::refaddr = \&Scalar::Util::refaddr;
1519 }
1520 else{ # This code is from Scalar::Util.
1521 # warn $@;
1522 eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
1523 *JSON::PP::blessed = sub {
1524 local($@, $SIG{__DIE__}, $SIG{__WARN__});
1525 ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
1526 };
1527 require B;
1528 my %tmap = qw(
1529 B::NULL SCALAR
1530 B::HV HASH
1531 B::AV ARRAY
1532 B::CV CODE
1533 B::IO IO
1534 B::GV GLOB
1535 B::REGEXP REGEXP
1536 );
1537 *JSON::PP::reftype = sub {
1538 my $r = shift;
1539
1540 return undef unless length(ref($r));
1541
1542 my $t = ref(B::svref_2object($r));
1543
1544 return
1545 exists $tmap{$t} ? $tmap{$t}
1546 : length(ref($$r)) ? 'REF'
1547 : 'SCALAR';
1548 };
1549 *JSON::PP::refaddr = sub {
1550 return undef unless length(ref($_[0]));
1551
1552 my $addr;
1553 if(defined(my $pkg = blessed($_[0]))) {
1554 $addr .= bless $_[0], 'Scalar::Util::Fake';
1555 bless $_[0], $pkg;
1556 }
1557 else {
1558 $addr .= $_[0]
1559 }
1560
1561 $addr =~ /0x(\w+)/;
1562 local $^W;
1563 #no warnings 'portable';
1564 hex($1);
1565 }
1566 }
1567 }
1568
1569
1570 # shamelessly copied and modified from JSON::XS code.
1571
1572 $JSON::PP::true = do { bless \(my $dummy = 1), "JSON::PP::Boolean" };
1573 $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" };
1574
1575 sub is_bool {
1576 if (blessed $_[0]) {
1577 return (
1578 $_[0]->isa("JSON::PP::Boolean")
1579 or $_[0]->isa("Types::Serialiser::BooleanBase")
1580 or $_[0]->isa("JSON::XS::Boolean")
1581 );
1582 }
1583 elsif (CORE_BOOL) {
1584 BEGIN { CORE_BOOL and warnings->unimport('experimental::builtin') }
1585 return builtin::is_bool($_[0]);
1586 }
1587 return !!0;
1588 }
1589
1590 sub true { $JSON::PP::true }
1591 sub false { $JSON::PP::false }
1592 sub null { undef; }
1593
1594 ###############################
1595
1596 package # hide from PAUSE
1597 JSON::PP::IncrParser;
1598
1599 use strict;
1600
1601 use constant INCR_M_WS => 0; # initial whitespace skipping
1602 use constant INCR_M_STR => 1; # inside string
1603 use constant INCR_M_BS => 2; # inside backslash
1604 use constant INCR_M_JSON => 3; # outside anything, count nesting
1605 use constant INCR_M_C0 => 4;
1606 use constant INCR_M_C1 => 5;
1607 use constant INCR_M_TFN => 6;
1608 use constant INCR_M_NUM => 7;
1609
1610 $JSON::backportPP::IncrParser::VERSION = '1.01';
1611
1612 sub new {
1613 my ( $class ) = @_;
1614
1615 bless {
1616 incr_nest => 0,
1617 incr_text => undef,
1618 incr_pos => 0,
1619 incr_mode => 0,
1620 }, $class;
1621 }
1622
1623
1624 sub incr_parse {
1625 my ( $self, $coder, $text ) = @_;
1626
1627 $self->{incr_text} = '' unless ( defined $self->{incr_text} );
1628
1629 if ( defined $text ) {
1630 $self->{incr_text} .= $text;
1631 }
1632
1633 if ( defined wantarray ) {
1634 my $max_size = $coder->get_max_size;
1635 my $p = $self->{incr_pos};
1636 my @ret;
1637 {
1638 do {
1639 unless ( $self->{incr_nest} <= 0 and $self->{incr_mode} == INCR_M_JSON ) {
1640 $self->_incr_parse( $coder );
1641
1642 if ( $max_size and $self->{incr_pos} > $max_size ) {
1643 Carp::croak("attempted decode of JSON text of $self->{incr_pos} bytes size, but max_size is set to $max_size");
1644 }
1645 unless ( $self->{incr_nest} <= 0 and $self->{incr_mode} == INCR_M_JSON ) {
1646 # as an optimisation, do not accumulate white space in the incr buffer
1647 if ( $self->{incr_mode} == INCR_M_WS and $self->{incr_pos} ) {
1648 $self->{incr_pos} = 0;
1649 $self->{incr_text} = '';
1650 }
1651 last;
1652 }
1653 }
1654
1655 unless ( $coder->get_utf8 ) {
1656 utf8::decode( $self->{incr_text} );
1657 }
1658
1659 my ($obj, $offset) = $coder->PP_decode_json( $self->{incr_text}, 0x00000001 );
1660 push @ret, $obj;
1661 use bytes;
1662 $self->{incr_text} = substr( $self->{incr_text}, $offset || 0 );
1663 $self->{incr_pos} = 0;
1664 $self->{incr_nest} = 0;
1665 $self->{incr_mode} = 0;
1666 last unless wantarray;
1667 } while ( wantarray );
1668 }
1669
1670 if ( wantarray ) {
1671 return @ret;
1672 }
1673 else { # in scalar context
1674 return defined $ret[0] ? $ret[0] : undef;
1675 }
1676 }
1677 }
1678
1679
1680 sub _incr_parse {
1681 my ($self, $coder) = @_;
1682 my $text = $self->{incr_text};
1683 my $len = length $text;
1684 my $p = $self->{incr_pos};
1685
1686 INCR_PARSE:
1687 while ( $len > $p ) {
1688 my $s = substr( $text, $p, 1 );
1689 last INCR_PARSE unless defined $s;
1690 my $mode = $self->{incr_mode};
1691
1692 if ( $mode == INCR_M_WS ) {
1693 while ( $len > $p ) {
1694 $s = substr( $text, $p, 1 );
1695 last INCR_PARSE unless defined $s;
1696 if ( ord($s) > ord " " ) {
1697 if ( $s eq '#' ) {
1698 $self->{incr_mode} = INCR_M_C0;
1699 redo INCR_PARSE;
1700 } else {
1701 $self->{incr_mode} = INCR_M_JSON;
1702 redo INCR_PARSE;
1703 }
1704 }
1705 $p++;
1706 }
1707 } elsif ( $mode == INCR_M_BS ) {
1708 $p++;
1709 $self->{incr_mode} = INCR_M_STR;
1710 redo INCR_PARSE;
1711 } elsif ( $mode == INCR_M_C0 or $mode == INCR_M_C1 ) {
1712 while ( $len > $p ) {
1713 $s = substr( $text, $p, 1 );
1714 last INCR_PARSE unless defined $s;
1715 if ( $s eq "\n" ) {
1716 $self->{incr_mode} = $self->{incr_mode} == INCR_M_C0 ? INCR_M_WS : INCR_M_JSON;
1717 last;
1718 }
1719 $p++;
1720 }
1721 next;
1722 } elsif ( $mode == INCR_M_TFN ) {
1723 last INCR_PARSE if $p >= $len && $self->{incr_nest};
1724 while ( $len > $p ) {
1725 $s = substr( $text, $p++, 1 );
1726 next if defined $s and $s =~ /[rueals]/;
1727 last;
1728 }
1729 $p--;
1730 $self->{incr_mode} = INCR_M_JSON;
1731
1732 last INCR_PARSE unless $self->{incr_nest};
1733 redo INCR_PARSE;
1734 } elsif ( $mode == INCR_M_NUM ) {
1735 last INCR_PARSE if $p >= $len && $self->{incr_nest};
1736 while ( $len > $p ) {
1737 $s = substr( $text, $p++, 1 );
1738 next if defined $s and $s =~ /[0-9eE.+\-]/;
1739 last;
1740 }
1741 $p--;
1742 $self->{incr_mode} = INCR_M_JSON;
1743
1744 last INCR_PARSE unless $self->{incr_nest};
1745 redo INCR_PARSE;
1746 } elsif ( $mode == INCR_M_STR ) {
1747 while ( $len > $p ) {
1748 $s = substr( $text, $p, 1 );
1749 last INCR_PARSE unless defined $s;
1750 if ( $s eq '"' ) {
1751 $p++;
1752 $self->{incr_mode} = INCR_M_JSON;
1753
1754 last INCR_PARSE unless $self->{incr_nest};
1755 redo INCR_PARSE;
1756 }
1757 elsif ( $s eq '\\' ) {
1758 $p++;
1759 if ( !defined substr($text, $p, 1) ) {
1760 $self->{incr_mode} = INCR_M_BS;
1761 last INCR_PARSE;
1762 }
1763 }
1764 $p++;
1765 }
1766 } elsif ( $mode == INCR_M_JSON ) {
1767 while ( $len > $p ) {
1768 $s = substr( $text, $p++, 1 );
1769 if ( $s eq "\x00" ) {
1770 $p--;
1771 last INCR_PARSE;
1772 } elsif ( $s =~ /^[\t\n\r ]$/) {
1773 if ( !$self->{incr_nest} ) {
1774 $p--; # do not eat the whitespace, let the next round do it
1775 last INCR_PARSE;
1776 }
1777 next;
1778 } elsif ( $s eq 't' or $s eq 'f' or $s eq 'n' ) {
1779 $self->{incr_mode} = INCR_M_TFN;
1780 redo INCR_PARSE;
1781 } elsif ( $s =~ /^[0-9\-]$/ ) {
1782 $self->{incr_mode} = INCR_M_NUM;
1783 redo INCR_PARSE;
1784 } elsif ( $s eq '"' ) {
1785 $self->{incr_mode} = INCR_M_STR;
1786 redo INCR_PARSE;
1787 } elsif ( $s eq '[' or $s eq '{' ) {
1788 if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
1789 Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
1790 }
1791 next;
1792 } elsif ( $s eq ']' or $s eq '}' ) {
1793 if ( --$self->{incr_nest} <= 0 ) {
1794 last INCR_PARSE;
1795 }
1796 } elsif ( $s eq '#' ) {
1797 $self->{incr_mode} = INCR_M_C1;
1798 redo INCR_PARSE;
1799 }
1800 }
1801 }
1802 }
1803
1804 $self->{incr_pos} = $p;
1805 $self->{incr_parsing} = $p ? 1 : 0; # for backward compatibility
1806 }
1807
1808
1809 sub incr_text {
1810 if ( $_[0]->{incr_pos} ) {
1811 Carp::croak("incr_text cannot be called when the incremental parser already started parsing");
1812 }
1813 $_[0]->{incr_text};
1814 }
1815
1816
1817 sub incr_skip {
1818 my $self = shift;
1819 $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_pos} );
1820 $self->{incr_pos} = 0;
1821 $self->{incr_mode} = 0;
1822 $self->{incr_nest} = 0;
1823 }
1824
1825
1826 sub incr_reset {
1827 my $self = shift;
1828 $self->{incr_text} = undef;
1829 $self->{incr_pos} = 0;
1830 $self->{incr_mode} = 0;
1831 $self->{incr_nest} = 0;
1832 }
1833
1834 ###############################
1835
1836
1837 1;
1838 __END__
1839 =pod
1840
1841 =head1 NAME
1842
1843 JSON::PP - JSON::XS compatible pure-Perl module.
1844
1845 =head1 SYNOPSIS
1846
1847 use JSON::PP;
1848
1849 # exported functions, they croak on error
1850 # and expect/generate UTF-8
1851
1852 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
1853 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
1854
1855 # OO-interface
1856
1857 $json = JSON::PP->new->ascii->pretty->allow_nonref;
1858
1859 $pretty_printed_json_text = $json->encode( $perl_scalar );
1860 $perl_scalar = $json->decode( $json_text );
1861
1862 # Note that JSON version 2.0 and above will automatically use
1863 # JSON::XS or JSON::PP, so you should be able to just:
1864
1865 use JSON;
1866
1867
1868 =head1 DESCRIPTION
1869
1870 JSON::PP is a pure perl JSON decoder/encoder, and (almost) compatible to much
1871 faster L<JSON::XS> written by Marc Lehmann in C. JSON::PP works as
1872 a fallback module when you use L<JSON> module without having
1873 installed JSON::XS.
1874
1875 Because of this fallback feature of JSON.pm, JSON::PP tries not to
1876 be more JavaScript-friendly than JSON::XS (i.e. not to escape extra
1877 characters such as U+2028 and U+2029, etc),
1878 in order for you not to lose such JavaScript-friendliness silently
1879 when you use JSON.pm and install JSON::XS for speed or by accident.
1880 If you need JavaScript-friendly RFC7159-compliant pure perl module,
1881 try L<JSON::Tiny>, which is derived from L<Mojolicious> web
1882 framework and is also smaller and faster than JSON::PP.
1883
1884 JSON::PP has been in the Perl core since Perl 5.14, mainly for
1885 CPAN toolchain modules to parse META.json.
1886
1887 =head1 FUNCTIONAL INTERFACE
1888
1889 This section is taken from JSON::XS almost verbatim. C<encode_json>
1890 and C<decode_json> are exported by default.
1891
1892 =head2 encode_json
1893
1894 $json_text = encode_json $perl_scalar
1895
1896 Converts the given Perl data structure to a UTF-8 encoded, binary string
1897 (that is, the string contains octets only). Croaks on error.
1898
1899 This function call is functionally identical to:
1900
1901 $json_text = JSON::PP->new->utf8->encode($perl_scalar)
1902
1903 Except being faster.
1904
1905 =head2 decode_json
1906
1907 $perl_scalar = decode_json $json_text
1908
1909 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
1910 to parse that as an UTF-8 encoded JSON text, returning the resulting
1911 reference. Croaks on error.
1912
1913 This function call is functionally identical to:
1914
1915 $perl_scalar = JSON::PP->new->utf8->decode($json_text)
1916
1917 Except being faster.
1918
1919 =head2 JSON::PP::is_bool
1920
1921 $is_boolean = JSON::PP::is_bool($scalar)
1922
1923 Returns true if the passed scalar represents either JSON::PP::true or
1924 JSON::PP::false, two constants that act like C<1> and C<0> respectively
1925 and are also used to represent JSON C<true> and C<false> in Perl strings.
1926
1927 On perl 5.36 and above, will also return true when given one of perl's
1928 standard boolean values, such as the result of a comparison.
1929
1930 See L<MAPPING>, below, for more information on how JSON values are mapped to
1931 Perl.
1932
1933 =head1 OBJECT-ORIENTED INTERFACE
1934
1935 This section is also taken from JSON::XS.
1936
1937 The object oriented interface lets you configure your own encoding or
1938 decoding style, within the limits of supported formats.
1939
1940 =head2 new
1941
1942 $json = JSON::PP->new
1943
1944 Creates a new JSON::PP object that can be used to de/encode JSON
1945 strings. All boolean flags described below are by default I<disabled>
1946 (with the exception of C<allow_nonref>, which defaults to I<enabled> since
1947 version C<4.0>).
1948
1949 The mutators for flags all return the JSON::PP object again and thus calls can
1950 be chained:
1951
1952 my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
1953 => {"a": [1, 2]}
1954
1955 =head2 ascii
1956
1957 $json = $json->ascii([$enable])
1958
1959 $enabled = $json->get_ascii
1960
1961 If C<$enable> is true (or missing), then the C<encode> method will not
1962 generate characters outside the code range C<0..127> (which is ASCII). Any
1963 Unicode characters outside that range will be escaped using either a
1964 single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence,
1965 as per RFC4627. The resulting encoded JSON text can be treated as a native
1966 Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string,
1967 or any other superset of ASCII.
1968
1969 If C<$enable> is false, then the C<encode> method will not escape Unicode
1970 characters unless required by the JSON syntax or other flags. This results
1971 in a faster and more compact format.
1972
1973 See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
1974
1975 The main use for this flag is to produce JSON texts that can be
1976 transmitted over a 7-bit channel, as the encoded JSON texts will not
1977 contain any 8 bit characters.
1978
1979 JSON::PP->new->ascii(1)->encode([chr 0x10401])
1980 => ["\ud801\udc01"]
1981
1982 =head2 latin1
1983
1984 $json = $json->latin1([$enable])
1985
1986 $enabled = $json->get_latin1
1987
1988 If C<$enable> is true (or missing), then the C<encode> method will encode
1989 the resulting JSON text as latin1 (or iso-8859-1), escaping any characters
1990 outside the code range C<0..255>. The resulting string can be treated as a
1991 latin1-encoded JSON text or a native Unicode string. The C<decode> method
1992 will not be affected in any way by this flag, as C<decode> by default
1993 expects Unicode, which is a strict superset of latin1.
1994
1995 If C<$enable> is false, then the C<encode> method will not escape Unicode
1996 characters unless required by the JSON syntax or other flags.
1997
1998 See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
1999
2000 The main use for this flag is efficiently encoding binary data as JSON
2001 text, as most octets will not be escaped, resulting in a smaller encoded
2002 size. The disadvantage is that the resulting JSON text is encoded
2003 in latin1 (and must correctly be treated as such when storing and
2004 transferring), a rare encoding for JSON. It is therefore most useful when
2005 you want to store data structures known to contain binary data efficiently
2006 in files or databases, not when talking to other JSON encoders/decoders.
2007
2008 JSON::PP->new->latin1->encode (["\x{89}\x{abc}"]
2009 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
2010
2011 =head2 utf8
2012
2013 $json = $json->utf8([$enable])
2014
2015 $enabled = $json->get_utf8
2016
2017 If C<$enable> is true (or missing), then the C<encode> method will encode
2018 the JSON result into UTF-8, as required by many protocols, while the
2019 C<decode> method expects to be handled an UTF-8-encoded string. Please
2020 note that UTF-8-encoded strings do not contain any characters outside the
2021 range C<0..255>, they are thus useful for bytewise/binary I/O. In future
2022 versions, enabling this option might enable autodetection of the UTF-16
2023 and UTF-32 encoding families, as described in RFC4627.
2024
2025 If C<$enable> is false, then the C<encode> method will return the JSON
2026 string as a (non-encoded) Unicode string, while C<decode> expects thus a
2027 Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
2028 to be done yourself, e.g. using the Encode module.
2029
2030 See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
2031
2032 Example, output UTF-16BE-encoded JSON:
2033
2034 use Encode;
2035 $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
2036
2037 Example, decode UTF-32LE-encoded JSON:
2038
2039 use Encode;
2040 $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
2041
2042 =head2 pretty
2043
2044 $json = $json->pretty([$enable])
2045
2046 This enables (or disables) all of the C<indent>, C<space_before> and
2047 C<space_after> (and in the future possibly more) flags in one call to
2048 generate the most readable (or most compact) form possible.
2049
2050 =head2 indent
2051
2052 $json = $json->indent([$enable])
2053
2054 $enabled = $json->get_indent
2055
2056 If C<$enable> is true (or missing), then the C<encode> method will use a multiline
2057 format as output, putting every array member or object/hash key-value pair
2058 into its own line, indenting them properly.
2059
2060 If C<$enable> is false, no newlines or indenting will be produced, and the
2061 resulting JSON text is guaranteed not to contain any C<newlines>.
2062
2063 This setting has no effect when decoding JSON texts.
2064
2065 The default indent space length is three.
2066 You can use C<indent_length> to change the length.
2067
2068 =head2 space_before
2069
2070 $json = $json->space_before([$enable])
2071
2072 $enabled = $json->get_space_before
2073
2074 If C<$enable> is true (or missing), then the C<encode> method will add an extra
2075 optional space before the C<:> separating keys from values in JSON objects.
2076
2077 If C<$enable> is false, then the C<encode> method will not add any extra
2078 space at those places.
2079
2080 This setting has no effect when decoding JSON texts. You will also
2081 most likely combine this setting with C<space_after>.
2082
2083 Example, space_before enabled, space_after and indent disabled:
2084
2085 {"key" :"value"}
2086
2087 =head2 space_after
2088
2089 $json = $json->space_after([$enable])
2090
2091 $enabled = $json->get_space_after
2092
2093 If C<$enable> is true (or missing), then the C<encode> method will add an extra
2094 optional space after the C<:> separating keys from values in JSON objects
2095 and extra whitespace after the C<,> separating key-value pairs and array
2096 members.
2097
2098 If C<$enable> is false, then the C<encode> method will not add any extra
2099 space at those places.
2100
2101 This setting has no effect when decoding JSON texts.
2102
2103 Example, space_before and indent disabled, space_after enabled:
2104
2105 {"key": "value"}
2106
2107 =head2 relaxed
2108
2109 $json = $json->relaxed([$enable])
2110
2111 $enabled = $json->get_relaxed
2112
2113 If C<$enable> is true (or missing), then C<decode> will accept some
2114 extensions to normal JSON syntax (see below). C<encode> will not be
2115 affected in anyway. I<Be aware that this option makes you accept invalid
2116 JSON texts as if they were valid!>. I suggest only to use this option to
2117 parse application-specific files written by humans (configuration files,
2118 resource files etc.)
2119
2120 If C<$enable> is false (the default), then C<decode> will only accept
2121 valid JSON texts.
2122
2123 Currently accepted extensions are:
2124
2125 =over 4
2126
2127 =item * list items can have an end-comma
2128
2129 JSON I<separates> array elements and key-value pairs with commas. This
2130 can be annoying if you write JSON texts manually and want to be able to
2131 quickly append elements, so this extension accepts comma at the end of
2132 such items not just between them:
2133
2134 [
2135 1,
2136 2, <- this comma not normally allowed
2137 ]
2138 {
2139 "k1": "v1",
2140 "k2": "v2", <- this comma not normally allowed
2141 }
2142
2143 =item * shell-style '#'-comments
2144
2145 Whenever JSON allows whitespace, shell-style comments are additionally
2146 allowed. They are terminated by the first carriage-return or line-feed
2147 character, after which more white-space and comments are allowed.
2148
2149 [
2150 1, # this comment not allowed in JSON
2151 # neither this one...
2152 ]
2153
2154 =item * C-style multiple-line '/* */'-comments (JSON::PP only)
2155
2156 Whenever JSON allows whitespace, C-style multiple-line comments are additionally
2157 allowed. Everything between C</*> and C<*/> is a comment, after which
2158 more white-space and comments are allowed.
2159
2160 [
2161 1, /* this comment not allowed in JSON */
2162 /* neither this one... */
2163 ]
2164
2165 =item * C++-style one-line '//'-comments (JSON::PP only)
2166
2167 Whenever JSON allows whitespace, C++-style one-line comments are additionally
2168 allowed. They are terminated by the first carriage-return or line-feed
2169 character, after which more white-space and comments are allowed.
2170
2171 [
2172 1, // this comment not allowed in JSON
2173 // neither this one...
2174 ]
2175
2176 =item * literal ASCII TAB characters in strings
2177
2178 Literal ASCII TAB characters are now allowed in strings (and treated as
2179 C<\t>).
2180
2181 [
2182 "Hello\tWorld",
2183 "Hello<TAB>World", # literal <TAB> would not normally be allowed
2184 ]
2185
2186 =back
2187
2188 =head2 canonical
2189
2190 $json = $json->canonical([$enable])
2191
2192 $enabled = $json->get_canonical
2193
2194 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
2195 by sorting their keys. This is adding a comparatively high overhead.
2196
2197 If C<$enable> is false, then the C<encode> method will output key-value
2198 pairs in the order Perl stores them (which will likely change between runs
2199 of the same script, and can change even within the same run from 5.18
2200 onwards).
2201
2202 This option is useful if you want the same data structure to be encoded as
2203 the same JSON text (given the same overall settings). If it is disabled,
2204 the same hash might be encoded differently even if contains the same data,
2205 as key-value pairs have no inherent ordering in Perl.
2206
2207 This setting has no effect when decoding JSON texts.
2208
2209 This setting has currently no effect on tied hashes.
2210
2211 =head2 allow_nonref
2212
2213 $json = $json->allow_nonref([$enable])
2214
2215 $enabled = $json->get_allow_nonref
2216
2217 Unlike other boolean options, this opotion is enabled by default beginning
2218 with version C<4.0>.
2219
2220 If C<$enable> is true (or missing), then the C<encode> method can convert a
2221 non-reference into its corresponding string, number or null JSON value,
2222 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
2223 values instead of croaking.
2224
2225 If C<$enable> is false, then the C<encode> method will croak if it isn't
2226 passed an arrayref or hashref, as JSON texts must either be an object
2227 or array. Likewise, C<decode> will croak if given something that is not a
2228 JSON object or array.
2229
2230 Example, encode a Perl scalar as JSON value without enabled C<allow_nonref>,
2231 resulting in an error:
2232
2233 JSON::PP->new->allow_nonref(0)->encode ("Hello, World!")
2234 => hash- or arrayref expected...
2235
2236 =head2 allow_unknown
2237
2238 $json = $json->allow_unknown([$enable])
2239
2240 $enabled = $json->get_allow_unknown
2241
2242 If C<$enable> is true (or missing), then C<encode> will I<not> throw an
2243 exception when it encounters values it cannot represent in JSON (for
2244 example, filehandles) but instead will encode a JSON C<null> value. Note
2245 that blessed objects are not included here and are handled separately by
2246 c<allow_blessed>.
2247
2248 If C<$enable> is false (the default), then C<encode> will throw an
2249 exception when it encounters anything it cannot encode as JSON.
2250
2251 This option does not affect C<decode> in any way, and it is recommended to
2252 leave it off unless you know your communications partner.
2253
2254 =head2 allow_blessed
2255
2256 $json = $json->allow_blessed([$enable])
2257
2258 $enabled = $json->get_allow_blessed
2259
2260 See L<OBJECT SERIALISATION> for details.
2261
2262 If C<$enable> is true (or missing), then the C<encode> method will not
2263 barf when it encounters a blessed reference that it cannot convert
2264 otherwise. Instead, a JSON C<null> value is encoded instead of the object.
2265
2266 If C<$enable> is false (the default), then C<encode> will throw an
2267 exception when it encounters a blessed object that it cannot convert
2268 otherwise.
2269
2270 This setting has no effect on C<decode>.
2271
2272 =head2 convert_blessed
2273
2274 $json = $json->convert_blessed([$enable])
2275
2276 $enabled = $json->get_convert_blessed
2277
2278 See L<OBJECT SERIALISATION> for details.
2279
2280 If C<$enable> is true (or missing), then C<encode>, upon encountering a
2281 blessed object, will check for the availability of the C<TO_JSON> method
2282 on the object's class. If found, it will be called in scalar context and
2283 the resulting scalar will be encoded instead of the object.
2284
2285 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
2286 returns other blessed objects, those will be handled in the same
2287 way. C<TO_JSON> must take care of not causing an endless recursion cycle
2288 (== crash) in this case. The name of C<TO_JSON> was chosen because other
2289 methods called by the Perl core (== not by the user of the object) are
2290 usually in upper case letters and to avoid collisions with any C<to_json>
2291 function or method.
2292
2293 If C<$enable> is false (the default), then C<encode> will not consider
2294 this type of conversion.
2295
2296 This setting has no effect on C<decode>.
2297
2298 =head2 allow_tags
2299
2300 $json = $json->allow_tags([$enable])
2301
2302 $enabled = $json->get_allow_tags
2303
2304 See L<OBJECT SERIALISATION> for details.
2305
2306 If C<$enable> is true (or missing), then C<encode>, upon encountering a
2307 blessed object, will check for the availability of the C<FREEZE> method on
2308 the object's class. If found, it will be used to serialise the object into
2309 a nonstandard tagged JSON value (that JSON decoders cannot decode).
2310
2311 It also causes C<decode> to parse such tagged JSON values and deserialise
2312 them via a call to the C<THAW> method.
2313
2314 If C<$enable> is false (the default), then C<encode> will not consider
2315 this type of conversion, and tagged JSON values will cause a parse error
2316 in C<decode>, as if tags were not part of the grammar.
2317
2318 =head2 boolean_values
2319
2320 $json->boolean_values([$false, $true])
2321
2322 ($false, $true) = $json->get_boolean_values
2323
2324 By default, JSON booleans will be decoded as overloaded
2325 C<$JSON::PP::false> and C<$JSON::PP::true> objects.
2326
2327 With this method you can specify your own boolean values for decoding -
2328 on decode, JSON C<false> will be decoded as a copy of C<$false>, and JSON
2329 C<true> will be decoded as C<$true> ("copy" here is the same thing as
2330 assigning a value to another variable, i.e. C<$copy = $false>).
2331
2332 This is useful when you want to pass a decoded data structure directly
2333 to other serialisers like YAML, Data::MessagePack and so on.
2334
2335 Note that this works only when you C<decode>. You can set incompatible
2336 boolean objects (like L<boolean>), but when you C<encode> a data structure
2337 with such boolean objects, you still need to enable C<convert_blessed>
2338 (and add a C<TO_JSON> method if necessary).
2339
2340 Calling this method without any arguments will reset the booleans
2341 to their default values.
2342
2343 C<get_boolean_values> will return both C<$false> and C<$true> values, or
2344 the empty list when they are set to the default.
2345
2346 =head2 core_bools
2347
2348 $json->core_bools([$enable]);
2349
2350 If C<$enable> is true (or missing), then C<decode>, will produce standard
2351 perl boolean values. Equivalent to calling:
2352
2353 $json->boolean_values(!!1, !!0)
2354
2355 C<get_core_bools> will return true if this has been set. On perl 5.36, it will
2356 also return true if the boolean values have been set to perl's core booleans
2357 using the C<boolean_values> method.
2358
2359 The methods C<unblessed_bool> and C<get_unblessed_bool> are provided as aliases
2360 for compatibility with L<Cpanel::JSON::XS>.
2361
2362 =head2 filter_json_object
2363
2364 $json = $json->filter_json_object([$coderef])
2365
2366 When C<$coderef> is specified, it will be called from C<decode> each
2367 time it decodes a JSON object. The only argument is a reference to
2368 the newly-created hash. If the code references returns a single scalar
2369 (which need not be a reference), this value (or rather a copy of it) is
2370 inserted into the deserialised data structure. If it returns an empty
2371 list (NOTE: I<not> C<undef>, which is a valid scalar), the original
2372 deserialised hash will be inserted. This setting can slow down decoding
2373 considerably.
2374
2375 When C<$coderef> is omitted or undefined, any existing callback will
2376 be removed and C<decode> will not change the deserialised hash in any
2377 way.
2378
2379 Example, convert all JSON objects into the integer 5:
2380
2381 my $js = JSON::PP->new->filter_json_object(sub { 5 });
2382 # returns [5]
2383 $js->decode('[{}]');
2384 # returns 5
2385 $js->decode('{"a":1, "b":2}');
2386
2387 =head2 filter_json_single_key_object
2388
2389 $json = $json->filter_json_single_key_object($key [=> $coderef])
2390
2391 Works remotely similar to C<filter_json_object>, but is only called for
2392 JSON objects having a single key named C<$key>.
2393
2394 This C<$coderef> is called before the one specified via
2395 C<filter_json_object>, if any. It gets passed the single value in the JSON
2396 object. If it returns a single value, it will be inserted into the data
2397 structure. If it returns nothing (not even C<undef> but the empty list),
2398 the callback from C<filter_json_object> will be called next, as if no
2399 single-key callback were specified.
2400
2401 If C<$coderef> is omitted or undefined, the corresponding callback will be
2402 disabled. There can only ever be one callback for a given key.
2403
2404 As this callback gets called less often then the C<filter_json_object>
2405 one, decoding speed will not usually suffer as much. Therefore, single-key
2406 objects make excellent targets to serialise Perl objects into, especially
2407 as single-key JSON objects are as close to the type-tagged value concept
2408 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
2409 support this in any way, so you need to make sure your data never looks
2410 like a serialised Perl hash.
2411
2412 Typical names for the single object key are C<__class_whatever__>, or
2413 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
2414 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
2415 with real hashes.
2416
2417 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
2418 into the corresponding C<< $WIDGET{<id>} >> object:
2419
2420 # return whatever is in $WIDGET{5}:
2421 JSON::PP
2422 ->new
2423 ->filter_json_single_key_object (__widget__ => sub {
2424 $WIDGET{ $_[0] }
2425 })
2426 ->decode ('{"__widget__": 5')
2427
2428 # this can be used with a TO_JSON method in some "widget" class
2429 # for serialisation to json:
2430 sub WidgetBase::TO_JSON {
2431 my ($self) = @_;
2432
2433 unless ($self->{id}) {
2434 $self->{id} = ..get..some..id..;
2435 $WIDGET{$self->{id}} = $self;
2436 }
2437
2438 { __widget__ => $self->{id} }
2439 }
2440
2441 =head2 shrink
2442
2443 $json = $json->shrink([$enable])
2444
2445 $enabled = $json->get_shrink
2446
2447 If C<$enable> is true (or missing), the string returned by C<encode> will
2448 be shrunk (i.e. downgraded if possible).
2449
2450 The actual definition of what shrink does might change in future versions,
2451 but it will always try to save space at the expense of time.
2452
2453 If C<$enable> is false, then JSON::PP does nothing.
2454
2455 =head2 max_depth
2456
2457 $json = $json->max_depth([$maximum_nesting_depth])
2458
2459 $max_depth = $json->get_max_depth
2460
2461 Sets the maximum nesting level (default C<512>) accepted while encoding
2462 or decoding. If a higher nesting level is detected in JSON text or a Perl
2463 data structure, then the encoder and decoder will stop and croak at that
2464 point.
2465
2466 Nesting level is defined by number of hash- or arrayrefs that the encoder
2467 needs to traverse to reach a given point or the number of C<{> or C<[>
2468 characters without their matching closing parenthesis crossed to reach a
2469 given character in a string.
2470
2471 Setting the maximum depth to one disallows any nesting, so that ensures
2472 that the object is only a single hash/object or array.
2473
2474 If no argument is given, the highest possible setting will be used, which
2475 is rarely useful.
2476
2477 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
2478
2479 =head2 max_size
2480
2481 $json = $json->max_size([$maximum_string_size])
2482
2483 $max_size = $json->get_max_size
2484
2485 Set the maximum length a JSON text may have (in bytes) where decoding is
2486 being attempted. The default is C<0>, meaning no limit. When C<decode>
2487 is called on a string that is longer then this many bytes, it will not
2488 attempt to decode the string but throw an exception. This setting has no
2489 effect on C<encode> (yet).
2490
2491 If no argument is given, the limit check will be deactivated (same as when
2492 C<0> is specified).
2493
2494 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
2495
2496 =head2 encode
2497
2498 $json_text = $json->encode($perl_scalar)
2499
2500 Converts the given Perl value or data structure to its JSON
2501 representation. Croaks on error.
2502
2503 =head2 decode
2504
2505 $perl_scalar = $json->decode($json_text)
2506
2507 The opposite of C<encode>: expects a JSON text and tries to parse it,
2508 returning the resulting simple scalar or reference. Croaks on error.
2509
2510 =head2 decode_prefix
2511
2512 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
2513
2514 This works like the C<decode> method, but instead of raising an exception
2515 when there is trailing garbage after the first JSON object, it will
2516 silently stop parsing there and return the number of characters consumed
2517 so far.
2518
2519 This is useful if your JSON texts are not delimited by an outer protocol
2520 and you need to know where the JSON text ends.
2521
2522 JSON::PP->new->decode_prefix ("[1] the tail")
2523 => ([1], 3)
2524
2525 =head1 FLAGS FOR JSON::PP ONLY
2526
2527 The following flags and properties are for JSON::PP only. If you use
2528 any of these, you can't make your application run faster by replacing
2529 JSON::PP with JSON::XS. If you need these and also speed boost,
2530 you might want to try L<Cpanel::JSON::XS>, a fork of JSON::XS by
2531 Reini Urban, which supports some of these (with a different set of
2532 incompatibilities). Most of these historical flags are only kept
2533 for backward compatibility, and should not be used in a new application.
2534
2535 =head2 allow_singlequote
2536
2537 $json = $json->allow_singlequote([$enable])
2538 $enabled = $json->get_allow_singlequote
2539
2540 If C<$enable> is true (or missing), then C<decode> will accept
2541 invalid JSON texts that contain strings that begin and end with
2542 single quotation marks. C<encode> will not be affected in any way.
2543 I<Be aware that this option makes you accept invalid JSON texts
2544 as if they were valid!>. I suggest only to use this option to
2545 parse application-specific files written by humans (configuration
2546 files, resource files etc.)
2547
2548 If C<$enable> is false (the default), then C<decode> will only accept
2549 valid JSON texts.
2550
2551 $json->allow_singlequote->decode(qq|{"foo":'bar'}|);
2552 $json->allow_singlequote->decode(qq|{'foo':"bar"}|);
2553 $json->allow_singlequote->decode(qq|{'foo':'bar'}|);
2554
2555 =head2 allow_barekey
2556
2557 $json = $json->allow_barekey([$enable])
2558 $enabled = $json->get_allow_barekey
2559
2560 If C<$enable> is true (or missing), then C<decode> will accept
2561 invalid JSON texts that contain JSON objects whose names don't
2562 begin and end with quotation marks. C<encode> will not be affected
2563 in any way. I<Be aware that this option makes you accept invalid JSON
2564 texts as if they were valid!>. I suggest only to use this option to
2565 parse application-specific files written by humans (configuration
2566 files, resource files etc.)
2567
2568 If C<$enable> is false (the default), then C<decode> will only accept
2569 valid JSON texts.
2570
2571 $json->allow_barekey->decode(qq|{foo:"bar"}|);
2572
2573 =head2 allow_bignum
2574
2575 $json = $json->allow_bignum([$enable])
2576 $enabled = $json->get_allow_bignum
2577
2578 If C<$enable> is true (or missing), then C<decode> will convert
2579 big integers Perl cannot handle as integer into L<Math::BigInt>
2580 objects and convert floating numbers into L<Math::BigFloat>
2581 objects. C<encode> will convert C<Math::BigInt> and C<Math::BigFloat>
2582 objects into JSON numbers.
2583
2584 $json->allow_nonref->allow_bignum;
2585 $bigfloat = $json->decode('2.000000000000000000000000001');
2586 print $json->encode($bigfloat);
2587 # => 2.000000000000000000000000001
2588
2589 See also L<MAPPING>.
2590
2591 =head2 loose
2592
2593 $json = $json->loose([$enable])
2594 $enabled = $json->get_loose
2595
2596 If C<$enable> is true (or missing), then C<decode> will accept
2597 invalid JSON texts that contain unescaped [\x00-\x1f\x22\x5c]
2598 characters. C<encode> will not be affected in any way.
2599 I<Be aware that this option makes you accept invalid JSON texts
2600 as if they were valid!>. I suggest only to use this option to
2601 parse application-specific files written by humans (configuration
2602 files, resource files etc.)
2603
2604 If C<$enable> is false (the default), then C<decode> will only accept
2605 valid JSON texts.
2606
2607 $json->loose->decode(qq|["abc
2608 def"]|);
2609
2610 =head2 escape_slash
2611
2612 $json = $json->escape_slash([$enable])
2613 $enabled = $json->get_escape_slash
2614
2615 If C<$enable> is true (or missing), then C<encode> will explicitly
2616 escape I<slash> (solidus; C<U+002F>) characters to reduce the risk of
2617 XSS (cross site scripting) that may be caused by C<< </script> >>
2618 in a JSON text, with the cost of bloating the size of JSON texts.
2619
2620 This option may be useful when you embed JSON in HTML, but embedding
2621 arbitrary JSON in HTML (by some HTML template toolkit or by string
2622 interpolation) is risky in general. You must escape necessary
2623 characters in correct order, depending on the context.
2624
2625 C<decode> will not be affected in any way.
2626
2627 =head2 indent_length
2628
2629 $json = $json->indent_length($number_of_spaces)
2630 $length = $json->get_indent_length
2631
2632 This option is only useful when you also enable C<indent> or C<pretty>.
2633
2634 JSON::XS indents with three spaces when you C<encode> (if requested
2635 by C<indent> or C<pretty>), and the number cannot be changed.
2636 JSON::PP allows you to change/get the number of indent spaces with these
2637 mutator/accessor. The default number of spaces is three (the same as
2638 JSON::XS), and the acceptable range is from C<0> (no indentation;
2639 it'd be better to disable indentation by C<indent(0)>) to C<15>.
2640
2641 =head2 sort_by
2642
2643 $json = $json->sort_by($code_ref)
2644 $json = $json->sort_by($subroutine_name)
2645
2646 If you just want to sort keys (names) in JSON objects when you
2647 C<encode>, enable C<canonical> option (see above) that allows you to
2648 sort object keys alphabetically.
2649
2650 If you do need to sort non-alphabetically for whatever reasons,
2651 you can give a code reference (or a subroutine name) to C<sort_by>,
2652 then the argument will be passed to Perl's C<sort> built-in function.
2653
2654 As the sorting is done in the JSON::PP scope, you usually need to
2655 prepend C<JSON::PP::> to the subroutine name, and the special variables
2656 C<$a> and C<$b> used in the subrontine used by C<sort> function.
2657
2658 Example:
2659
2660 my %ORDER = (id => 1, class => 2, name => 3);
2661 $json->sort_by(sub {
2662 ($ORDER{$JSON::PP::a} // 999) <=> ($ORDER{$JSON::PP::b} // 999)
2663 or $JSON::PP::a cmp $JSON::PP::b
2664 });
2665 print $json->encode([
2666 {name => 'CPAN', id => 1, href => 'http://cpan.org'}
2667 ]);
2668 # [{"id":1,"name":"CPAN","href":"http://cpan.org"}]
2669
2670 Note that C<sort_by> affects all the plain hashes in the data structure.
2671 If you need finer control, C<tie> necessary hashes with a module that
2672 implements ordered hash (such as L<Hash::Ordered> and L<Tie::IxHash>).
2673 C<canonical> and C<sort_by> don't affect the key order in C<tie>d
2674 hashes.
2675
2676 use Hash::Ordered;
2677 tie my %hash, 'Hash::Ordered',
2678 (name => 'CPAN', id => 1, href => 'http://cpan.org');
2679 print $json->encode([\%hash]);
2680 # [{"name":"CPAN","id":1,"href":"http://cpan.org"}] # order is kept
2681
2682 =head1 INCREMENTAL PARSING
2683
2684 This section is also taken from JSON::XS.
2685
2686 In some cases, there is the need for incremental parsing of JSON
2687 texts. While this module always has to keep both JSON text and resulting
2688 Perl data structure in memory at one time, it does allow you to parse a
2689 JSON stream incrementally. It does so by accumulating text until it has
2690 a full JSON object, which it then can decode. This process is similar to
2691 using C<decode_prefix> to see if a full JSON object is available, but
2692 is much more efficient (and can be implemented with a minimum of method
2693 calls).
2694
2695 JSON::PP will only attempt to parse the JSON text once it is sure it
2696 has enough text to get a decisive result, using a very simple but
2697 truly incremental parser. This means that it sometimes won't stop as
2698 early as the full parser, for example, it doesn't detect mismatched
2699 parentheses. The only thing it guarantees is that it starts decoding as
2700 soon as a syntactically valid JSON text has been seen. This means you need
2701 to set resource limits (e.g. C<max_size>) to ensure the parser will stop
2702 parsing in the presence if syntax errors.
2703
2704 The following methods implement this incremental parser.
2705
2706 =head2 incr_parse
2707
2708 $json->incr_parse( [$string] ) # void context
2709
2710 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
2711
2712 @obj_or_empty = $json->incr_parse( [$string] ) # list context
2713
2714 This is the central parsing function. It can both append new text and
2715 extract objects from the stream accumulated so far (both of these
2716 functions are optional).
2717
2718 If C<$string> is given, then this string is appended to the already
2719 existing JSON fragment stored in the C<$json> object.
2720
2721 After that, if the function is called in void context, it will simply
2722 return without doing anything further. This can be used to add more text
2723 in as many chunks as you want.
2724
2725 If the method is called in scalar context, then it will try to extract
2726 exactly I<one> JSON object. If that is successful, it will return this
2727 object, otherwise it will return C<undef>. If there is a parse error,
2728 this method will croak just as C<decode> would do (one can then use
2729 C<incr_skip> to skip the erroneous part). This is the most common way of
2730 using the method.
2731
2732 And finally, in list context, it will try to extract as many objects
2733 from the stream as it can find and return them, or the empty list
2734 otherwise. For this to work, there must be no separators (other than
2735 whitespace) between the JSON objects or arrays, instead they must be
2736 concatenated back-to-back. If an error occurs, an exception will be
2737 raised as in the scalar context case. Note that in this case, any
2738 previously-parsed JSON texts will be lost.
2739
2740 Example: Parse some JSON arrays/objects in a given string and return
2741 them.
2742
2743 my @objs = JSON::PP->new->incr_parse ("[5][7][1,2]");
2744
2745 =head2 incr_text
2746
2747 $lvalue_string = $json->incr_text
2748
2749 This method returns the currently stored JSON fragment as an lvalue, that
2750 is, you can manipulate it. This I<only> works when a preceding call to
2751 C<incr_parse> in I<scalar context> successfully returned an object. Under
2752 all other circumstances you must not call this function (I mean it.
2753 although in simple tests it might actually work, it I<will> fail under
2754 real world conditions). As a special exception, you can also call this
2755 method before having parsed anything.
2756
2757 That means you can only use this function to look at or manipulate text
2758 before or after complete JSON objects, not while the parser is in the
2759 middle of parsing a JSON object.
2760
2761 This function is useful in two cases: a) finding the trailing text after a
2762 JSON object or b) parsing multiple JSON objects separated by non-JSON text
2763 (such as commas).
2764
2765 =head2 incr_skip
2766
2767 $json->incr_skip
2768
2769 This will reset the state of the incremental parser and will remove
2770 the parsed text from the input buffer so far. This is useful after
2771 C<incr_parse> died, in which case the input buffer and incremental parser
2772 state is left unchanged, to skip the text parsed so far and to reset the
2773 parse state.
2774
2775 The difference to C<incr_reset> is that only text until the parse error
2776 occurred is removed.
2777
2778 =head2 incr_reset
2779
2780 $json->incr_reset
2781
2782 This completely resets the incremental parser, that is, after this call,
2783 it will be as if the parser had never parsed anything.
2784
2785 This is useful if you want to repeatedly parse JSON objects and want to
2786 ignore any trailing data, which means you have to reset the parser after
2787 each successful decode.
2788
2789 =head1 MAPPING
2790
2791 Most of this section is also taken from JSON::XS.
2792
2793 This section describes how JSON::PP maps Perl values to JSON values and
2794 vice versa. These mappings are designed to "do the right thing" in most
2795 circumstances automatically, preserving round-tripping characteristics
2796 (what you put in comes out as something equivalent).
2797
2798 For the more enlightened: note that in the following descriptions,
2799 lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl>
2800 refers to the abstract Perl language itself.
2801
2802 =head2 JSON -> PERL
2803
2804 =over 4
2805
2806 =item object
2807
2808 A JSON object becomes a reference to a hash in Perl. No ordering of object
2809 keys is preserved (JSON does not preserve object key ordering itself).
2810
2811 =item array
2812
2813 A JSON array becomes a reference to an array in Perl.
2814
2815 =item string
2816
2817 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
2818 are represented by the same codepoints in the Perl string, so no manual
2819 decoding is necessary.
2820
2821 =item number
2822
2823 A JSON number becomes either an integer, numeric (floating point) or
2824 string scalar in perl, depending on its range and any fractional parts. On
2825 the Perl level, there is no difference between those as Perl handles all
2826 the conversion details, but an integer may take slightly less memory and
2827 might represent more values exactly than floating point numbers.
2828
2829 If the number consists of digits only, JSON::PP will try to represent
2830 it as an integer value. If that fails, it will try to represent it as
2831 a numeric (floating point) value if that is possible without loss of
2832 precision. Otherwise it will preserve the number as a string value (in
2833 which case you lose roundtripping ability, as the JSON number will be
2834 re-encoded to a JSON string).
2835
2836 Numbers containing a fractional or exponential part will always be
2837 represented as numeric (floating point) values, possibly at a loss of
2838 precision (in which case you might lose perfect roundtripping ability, but
2839 the JSON number will still be re-encoded as a JSON number).
2840
2841 Note that precision is not accuracy - binary floating point values cannot
2842 represent most decimal fractions exactly, and when converting from and to
2843 floating point, JSON::PP only guarantees precision up to but not including
2844 the least significant bit.
2845
2846 When C<allow_bignum> is enabled, big integer values and any numeric
2847 values will be converted into L<Math::BigInt> and L<Math::BigFloat>
2848 objects respectively, without becoming string scalars or losing
2849 precision.
2850
2851 =item true, false
2852
2853 These JSON atoms become C<JSON::PP::true> and C<JSON::PP::false>,
2854 respectively. They are overloaded to act almost exactly like the numbers
2855 C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
2856 the C<JSON::PP::is_bool> function.
2857
2858 =item null
2859
2860 A JSON null atom becomes C<undef> in Perl.
2861
2862 =item shell-style comments (C<< # I<text> >>)
2863
2864 As a nonstandard extension to the JSON syntax that is enabled by the
2865 C<relaxed> setting, shell-style comments are allowed. They can start
2866 anywhere outside strings and go till the end of the line.
2867
2868 =item tagged values (C<< (I<tag>)I<value> >>).
2869
2870 Another nonstandard extension to the JSON syntax, enabled with the
2871 C<allow_tags> setting, are tagged values. In this implementation, the
2872 I<tag> must be a perl package/class name encoded as a JSON string, and the
2873 I<value> must be a JSON array encoding optional constructor arguments.
2874
2875 See L<OBJECT SERIALISATION>, below, for details.
2876
2877 =back
2878
2879
2880 =head2 PERL -> JSON
2881
2882 The mapping from Perl to JSON is slightly more difficult, as Perl is a
2883 truly typeless language, so we can only guess which JSON type is meant by
2884 a Perl value.
2885
2886 =over 4
2887
2888 =item hash references
2889
2890 Perl hash references become JSON objects. As there is no inherent
2891 ordering in hash keys (or JSON objects), they will usually be encoded
2892 in a pseudo-random order. JSON::PP can optionally sort the hash keys
2893 (determined by the I<canonical> flag and/or I<sort_by> property), so
2894 the same data structure will serialise to the same JSON text (given
2895 same settings and version of JSON::PP), but this incurs a runtime
2896 overhead and is only rarely useful, e.g. when you want to compare some
2897 JSON text against another for equality.
2898
2899 =item array references
2900
2901 Perl array references become JSON arrays.
2902
2903 =item other references
2904
2905 Other unblessed references are generally not allowed and will cause an
2906 exception to be thrown, except for references to the integers C<0> and
2907 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
2908 also use C<JSON::PP::false> and C<JSON::PP::true> to improve
2909 readability.
2910
2911 to_json [\0, JSON::PP::true] # yields [false,true]
2912
2913 =item JSON::PP::true, JSON::PP::false
2914
2915 These special values become JSON true and JSON false values,
2916 respectively. You can also use C<\1> and C<\0> directly if you want.
2917
2918 =item JSON::PP::null
2919
2920 This special value becomes JSON null.
2921
2922 =item blessed objects
2923
2924 Blessed objects are not directly representable in JSON, but C<JSON::PP>
2925 allows various ways of handling objects. See L<OBJECT SERIALISATION>,
2926 below, for details.
2927
2928 =item simple scalars
2929
2930 Simple Perl scalars (any scalar that is not a reference) are the most
2931 difficult objects to encode: JSON::PP will encode undefined scalars as
2932 JSON C<null> values, scalars that have last been used in a string context
2933 before encoding as JSON strings, and anything else as number value:
2934
2935 # dump as number
2936 encode_json [2] # yields [2]
2937 encode_json [-3.0e17] # yields [-3e+17]
2938 my $value = 5; encode_json [$value] # yields [5]
2939
2940 # used as string, so dump as string
2941 print $value;
2942 encode_json [$value] # yields ["5"]
2943
2944 # undef becomes null
2945 encode_json [undef] # yields [null]
2946
2947 You can force the type to be a JSON string by stringifying it:
2948
2949 my $x = 3.1; # some variable containing a number
2950 "$x"; # stringified
2951 $x .= ""; # another, more awkward way to stringify
2952 print $x; # perl does it for you, too, quite often
2953 # (but for older perls)
2954
2955 You can force the type to be a JSON number by numifying it:
2956
2957 my $x = "3"; # some variable containing a string
2958 $x += 0; # numify it, ensuring it will be dumped as a number
2959 $x *= 1; # same thing, the choice is yours.
2960
2961 You can not currently force the type in other, less obscure, ways.
2962
2963 Since version 2.91_01, JSON::PP uses a different number detection logic
2964 that converts a scalar that is possible to turn into a number safely.
2965 The new logic is slightly faster, and tends to help people who use older
2966 perl or who want to encode complicated data structure. However, this may
2967 results in a different JSON text from the one JSON::XS encodes (and
2968 thus may break tests that compare entire JSON texts). If you do
2969 need the previous behavior for compatibility or for finer control,
2970 set PERL_JSON_PP_USE_B environmental variable to true before you
2971 C<use> JSON::PP (or JSON.pm).
2972
2973 Note that numerical precision has the same meaning as under Perl (so
2974 binary to decimal conversion follows the same rules as in Perl, which
2975 can differ to other languages). Also, your perl interpreter might expose
2976 extensions to the floating point numbers of your platform, such as
2977 infinities or NaN's - these cannot be represented in JSON, and it is an
2978 error to pass those in.
2979
2980 JSON::PP (and JSON::XS) trusts what you pass to C<encode> method
2981 (or C<encode_json> function) is a clean, validated data structure with
2982 values that can be represented as valid JSON values only, because it's
2983 not from an external data source (as opposed to JSON texts you pass to
2984 C<decode> or C<decode_json>, which JSON::PP considers tainted and
2985 doesn't trust). As JSON::PP doesn't know exactly what you and consumers
2986 of your JSON texts want the unexpected values to be (you may want to
2987 convert them into null, or to stringify them with or without
2988 normalisation (string representation of infinities/NaN may vary
2989 depending on platforms), or to croak without conversion), you're advised
2990 to do what you and your consumers need before you encode, and also not
2991 to numify values that may start with values that look like a number
2992 (including infinities/NaN), without validating.
2993
2994 =back
2995
2996 =head2 OBJECT SERIALISATION
2997
2998 As JSON cannot directly represent Perl objects, you have to choose between
2999 a pure JSON representation (without the ability to deserialise the object
3000 automatically again), and a nonstandard extension to the JSON syntax,
3001 tagged values.
3002
3003 =head3 SERIALISATION
3004
3005 What happens when C<JSON::PP> encounters a Perl object depends on the
3006 C<allow_blessed>, C<convert_blessed>, C<allow_tags> and C<allow_bignum>
3007 settings, which are used in this order:
3008
3009 =over 4
3010
3011 =item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method.
3012
3013 In this case, C<JSON::PP> creates a tagged JSON value, using a nonstandard
3014 extension to the JSON syntax.
3015
3016 This works by invoking the C<FREEZE> method on the object, with the first
3017 argument being the object to serialise, and the second argument being the
3018 constant string C<JSON> to distinguish it from other serialisers.
3019
3020 The C<FREEZE> method can return any number of values (i.e. zero or
3021 more). These values and the paclkage/classname of the object will then be
3022 encoded as a tagged JSON value in the following format:
3023
3024 ("classname")[FREEZE return values...]
3025
3026 e.g.:
3027
3028 ("URI")["http://www.google.com/"]
3029 ("MyDate")[2013,10,29]
3030 ("ImageData::JPEG")["Z3...VlCg=="]
3031
3032 For example, the hypothetical C<My::Object> C<FREEZE> method might use the
3033 objects C<type> and C<id> members to encode the object:
3034
3035 sub My::Object::FREEZE {
3036 my ($self, $serialiser) = @_;
3037
3038 ($self->{type}, $self->{id})
3039 }
3040
3041 =item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method.
3042
3043 In this case, the C<TO_JSON> method of the object is invoked in scalar
3044 context. It must return a single scalar that can be directly encoded into
3045 JSON. This scalar replaces the object in the JSON text.
3046
3047 For example, the following C<TO_JSON> method will convert all L<URI>
3048 objects to JSON strings when serialised. The fact that these values
3049 originally were L<URI> objects is lost.
3050
3051 sub URI::TO_JSON {
3052 my ($uri) = @_;
3053 $uri->as_string
3054 }
3055
3056 =item 3. C<allow_bignum> is enabled and the object is a C<Math::BigInt> or C<Math::BigFloat>.
3057
3058 The object will be serialised as a JSON number value.
3059
3060 =item 4. C<allow_blessed> is enabled.
3061
3062 The object will be serialised as a JSON null value.
3063
3064 =item 5. none of the above
3065
3066 If none of the settings are enabled or the respective methods are missing,
3067 C<JSON::PP> throws an exception.
3068
3069 =back
3070
3071 =head3 DESERIALISATION
3072
3073 For deserialisation there are only two cases to consider: either
3074 nonstandard tagging was used, in which case C<allow_tags> decides,
3075 or objects cannot be automatically be deserialised, in which
3076 case you can use postprocessing or the C<filter_json_object> or
3077 C<filter_json_single_key_object> callbacks to get some real objects our of
3078 your JSON.
3079
3080 This section only considers the tagged value case: a tagged JSON object
3081 is encountered during decoding and C<allow_tags> is disabled, a parse
3082 error will result (as if tagged values were not part of the grammar).
3083
3084 If C<allow_tags> is enabled, C<JSON::PP> will look up the C<THAW> method
3085 of the package/classname used during serialisation (it will not attempt
3086 to load the package as a Perl module). If there is no such method, the
3087 decoding will fail with an error.
3088
3089 Otherwise, the C<THAW> method is invoked with the classname as first
3090 argument, the constant string C<JSON> as second argument, and all the
3091 values from the JSON array (the values originally returned by the
3092 C<FREEZE> method) as remaining arguments.
3093
3094 The method must then return the object. While technically you can return
3095 any Perl scalar, you might have to enable the C<allow_nonref> setting to
3096 make that work in all cases, so better return an actual blessed reference.
3097
3098 As an example, let's implement a C<THAW> function that regenerates the
3099 C<My::Object> from the C<FREEZE> example earlier:
3100
3101 sub My::Object::THAW {
3102 my ($class, $serialiser, $type, $id) = @_;
3103
3104 $class->new (type => $type, id => $id)
3105 }
3106
3107
3108 =head1 ENCODING/CODESET FLAG NOTES
3109
3110 This section is taken from JSON::XS.
3111
3112 The interested reader might have seen a number of flags that signify
3113 encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be
3114 some confusion on what these do, so here is a short comparison:
3115
3116 C<utf8> controls whether the JSON text created by C<encode> (and expected
3117 by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only
3118 control whether C<encode> escapes character values outside their respective
3119 codeset range. Neither of these flags conflict with each other, although
3120 some combinations make less sense than others.
3121
3122 Care has been taken to make all flags symmetrical with respect to
3123 C<encode> and C<decode>, that is, texts encoded with any combination of
3124 these flag values will be correctly decoded when the same flags are used
3125 - in general, if you use different flag settings while encoding vs. when
3126 decoding you likely have a bug somewhere.
3127
3128 Below comes a verbose discussion of these flags. Note that a "codeset" is
3129 simply an abstract set of character-codepoint pairs, while an encoding
3130 takes those codepoint numbers and I<encodes> them, in our case into
3131 octets. Unicode is (among other things) a codeset, UTF-8 is an encoding,
3132 and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at
3133 the same time, which can be confusing.
3134
3135 =over 4
3136
3137 =item C<utf8> flag disabled
3138
3139 When C<utf8> is disabled (the default), then C<encode>/C<decode> generate
3140 and expect Unicode strings, that is, characters with high ordinal Unicode
3141 values (> 255) will be encoded as such characters, and likewise such
3142 characters are decoded as-is, no changes to them will be done, except
3143 "(re-)interpreting" them as Unicode codepoints or Unicode characters,
3144 respectively (to Perl, these are the same thing in strings unless you do
3145 funny/weird/dumb stuff).
3146
3147 This is useful when you want to do the encoding yourself (e.g. when you
3148 want to have UTF-16 encoded JSON texts) or when some other layer does
3149 the encoding for you (for example, when printing to a terminal using a
3150 filehandle that transparently encodes to UTF-8 you certainly do NOT want
3151 to UTF-8 encode your data first and have Perl encode it another time).
3152
3153 =item C<utf8> flag enabled
3154
3155 If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all
3156 characters using the corresponding UTF-8 multi-byte sequence, and will
3157 expect your input strings to be encoded as UTF-8, that is, no "character"
3158 of the input string must have any value > 255, as UTF-8 does not allow
3159 that.
3160
3161 The C<utf8> flag therefore switches between two modes: disabled means you
3162 will get a Unicode string in Perl, enabled means you get an UTF-8 encoded
3163 octet/binary string in Perl.
3164
3165 =item C<latin1> or C<ascii> flags enabled
3166
3167 With C<latin1> (or C<ascii>) enabled, C<encode> will escape characters
3168 with ordinal values > 255 (> 127 with C<ascii>) and encode the remaining
3169 characters as specified by the C<utf8> flag.
3170
3171 If C<utf8> is disabled, then the result is also correctly encoded in those
3172 character sets (as both are proper subsets of Unicode, meaning that a
3173 Unicode string with all character values < 256 is the same thing as a
3174 ISO-8859-1 string, and a Unicode string with all character values < 128 is
3175 the same thing as an ASCII string in Perl).
3176
3177 If C<utf8> is enabled, you still get a correct UTF-8-encoded string,
3178 regardless of these flags, just some more characters will be escaped using
3179 C<\uXXXX> then before.
3180
3181 Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8
3182 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1
3183 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being
3184 a subset of Unicode), while ASCII is.
3185
3186 Surprisingly, C<decode> will ignore these flags and so treat all input
3187 values as governed by the C<utf8> flag. If it is disabled, this allows you
3188 to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of
3189 Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.
3190
3191 So neither C<latin1> nor C<ascii> are incompatible with the C<utf8> flag -
3192 they only govern when the JSON output engine escapes a character or not.
3193
3194 The main use for C<latin1> is to relatively efficiently store binary data
3195 as JSON, at the expense of breaking compatibility with most JSON decoders.
3196
3197 The main use for C<ascii> is to force the output to not contain characters
3198 with values > 127, which means you can interpret the resulting string
3199 as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and
3200 8-bit-encoding, and still get the same data structure back. This is useful
3201 when your channel for JSON transfer is not 8-bit clean or the encoding
3202 might be mangled in between (e.g. in mail), and works because ASCII is a
3203 proper subset of most 8-bit and multibyte encodings in use in the world.
3204
3205 =back
3206
3207 =head1 BUGS
3208
3209 Please report bugs on a specific behavior of this module to RT or GitHub
3210 issues (preferred):
3211
3212 L<https://github.com/makamaka/JSON-PP/issues>
3213
3214 L<https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON-PP>
3215
3216 As for new features and requests to change common behaviors, please
3217 ask the author of JSON::XS (Marc Lehmann, E<lt>schmorp[at]schmorp.deE<gt>)
3218 first, by email (important!), to keep compatibility among JSON.pm backends.
3219
3220 Generally speaking, if you need something special for you, you are advised
3221 to create a new module, maybe based on L<JSON::Tiny>, which is smaller and
3222 written in a much cleaner way than this module.
3223
3224 =head1 SEE ALSO
3225
3226 The F<json_pp> command line utility for quick experiments.
3227
3228 L<JSON::XS>, L<Cpanel::JSON::XS>, and L<JSON::Tiny> for faster alternatives.
3229 L<JSON> and L<JSON::MaybeXS> for easy migration.
3230
3231 L<JSON::backportPP::Compat5005> and L<JSON::backportPP::Compat5006> for older perl users.
3232
3233 RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>)
3234
3235 RFC7159 (L<http://www.ietf.org/rfc/rfc7159.txt>)
3236
3237 RFC8259 (L<http://www.ietf.org/rfc/rfc8259.txt>)
3238
3239 =head1 AUTHOR
3240
3241 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
3242
3243 =head1 CURRENT MAINTAINER
3244
3245 Kenichi Ishigaki, E<lt>ishigaki[at]cpan.orgE<gt>
3246
3247 =head1 COPYRIGHT AND LICENSE
3248
3249 Copyright 2007-2016 by Makamaka Hannyaharamitu
3250
3251 Most of the documentation is taken from JSON::XS by Marc Lehmann
3252
3253 This library is free software; you can redistribute it and/or modify
3254 it under the same terms as Perl itself.
3255
3256 =cut