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