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