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