7 @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
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 };
15 my $Module_XS = 'JSON::XS';
16 my $Module_PP = 'JSON::PP';
17 my $Module_bp = 'JSON::backportPP'; # included in JSON distribution
18 my $PP_Version = '2.27200';
19 my $XS_Version = '2.34';
22 # XS and PP common methods
24 my @PublicMethods = qw/
25 ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref
26 allow_blessed convert_blessed filter_json_object filter_json_single_key_object
27 shrink max_depth max_size encode decode decode_prefix allow_unknown
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
35 my @XSOnlyMethods = qw//; # Currently nothing
37 my @PPOnlyMethods = qw/
39 allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed
40 /; # JSON::PP specific
43 # used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently)
44 my $_INSTALL_DONT_DIE = 1; # When _load_xs fails to load XS, don't die.
45 my $_INSTALL_ONLY = 2; # Don't call _set_methods()
46 my $_ALLOW_UNSUPPORTED = 0;
47 my $_UNIV_CONV_BLESSED = 0;
51 # Check the environment variable to decide worker module.
53 unless ($JSON::Backend) {
54 $JSON::DEBUG and Carp::carp("Check used worker module...");
56 my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1;
58 if ($backend eq '1' or $backend =~ /JSON::XS\s*,\s*JSON::PP/) {
59 _load_xs($_INSTALL_DONT_DIE) or _load_pp();
61 elsif ($backend eq '0' or $backend eq 'JSON::PP') {
64 elsif ($backend eq '2' or $backend eq 'JSON::XS') {
67 elsif ($backend eq 'JSON::backportPP') {
72 Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid.";
83 if ($tag eq '-support_by_pp') {
84 if (!$_ALLOW_UNSUPPORTED++) {
86 ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend eq $Module_XS);
90 elsif ($tag eq '-no_export') {
93 elsif ( $tag eq '-convert_blessed_universally' ) {
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] } ]
103 | if ( !$_UNIV_CONV_BLESSED++ );
106 push @what_to_export, $tag;
109 return if ($no_export);
111 __PACKAGE__->export_to_level(1, $pkg, @what_to_export);
118 my $alternative = 'from_json';
119 if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
120 shift @_; $alternative = 'decode';
122 Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead.";
123 return JSON::from_json(@_);
127 my $alternative = 'to_json';
128 if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
129 shift @_; $alternative = 'encode';
131 Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead.";
141 or (@_ > 2 and $_[0] eq 'JSON')
143 Carp::croak "to_json should not be called as a method.";
145 my $json = JSON->new;
147 if (@_ == 2 and ref $_[1] eq 'HASH') {
149 for my $method (keys %$opt) {
150 $json->$method( $opt->{$method} );
154 $json->encode($_[0]);
159 if ( ref($_[0]) eq 'JSON' or $_[0] eq 'JSON' ) {
160 Carp::croak "from_json should not be called as a method.";
162 my $json = JSON->new;
164 if (@_ == 2 and ref $_[1] eq 'HASH') {
166 for my $method (keys %$opt) {
167 $json->$method( $opt->{$method} );
171 return $json->decode( $_[0] );
175 sub true { $JSON::true }
177 sub false { $JSON::false }
182 sub require_xs_version { $XS_Version; }
193 return $_[0]->module eq $Module_XS;
198 return not $_[0]->xs;
202 sub pureperl_only_methods { @PPOnlyMethods; }
206 my ($self, $name, $value) = @_;
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;
217 $props{$name} = $self->$method();
222 Carp::croak('property() can take only the option within 2 arguments.');
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;
234 $self->$name($value);
246 $JSON::DEBUG and Carp::carp "Load $Module_XS.";
248 # if called after install module, overload is disable.... why?
249 JSON::Boolean::_overrride_overload($Module_XS);
250 JSON::Boolean::_overrride_overload($Module_PP);
253 use $Module_XS $XS_Version ();
257 if (defined $opt and $opt & $_INSTALL_DONT_DIE) {
258 $JSON::DEBUG and Carp::carp "Can't load $Module_XS...($@)";
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.
269 JSON::Backend::XS->init;
278 my $backend = $_USSING_bpPP ? $Module_bp : $Module_PP;
280 $JSON::DEBUG and Carp::carp "Load $backend.";
282 # if called after install module, overload is disable.... why?
283 JSON::Boolean::_overrride_overload($Module_XS);
284 JSON::Boolean::_overrride_overload($backend);
286 if ( $_USSING_bpPP ) {
287 eval qq| require $backend |;
290 eval qq| use $backend $PP_Version () |;
294 if ( $backend eq $Module_PP ) {
295 $JSON::DEBUG and Carp::carp "Can't load $Module_PP ($@), so try to load $Module_bp";
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 |;
302 Carp::croak $@ if $@;
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;
313 return if defined $JSON::true;
320 $JSON::true = ${"$module\::true"};
321 $JSON::false = ${"$module\::false"};
323 push @JSON::ISA, $module;
324 push @{"$module\::Boolean::ISA"}, qw(JSON::Boolean);
326 *{"JSON::is_bool"} = \&{"$module\::is_bool"};
328 for my $method ($module eq $Module_XS ? @PPOnlyMethods : @XSOnlyMethods) {
329 *{"JSON::$method"} = sub {
330 Carp::carp("$method is not supported in $module.");
344 package JSON::Boolean;
348 sub _overrride_overload {
349 return if ($Installed{ $_[0] }++);
351 my $boolean = $_[0] . '::Boolean';
356 '""' => sub { ${$_[0]} == 1 ? 'true' : 'false' },
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;
363 return $obj ? 1 == $op : 0 == $op;
369 if ($@) { Carp::croak $@; }
371 if ( exists $INC{'JSON/XS.pm'} and $boolean eq 'JSON::XS::Boolean' ) {
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 };
378 elsif ( exists $INC{'JSON/PP.pm'} and $boolean eq 'JSON::PP::Boolean' ) {
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 };
391 # Helper classes for Backend Module (PP)
394 package JSON::Backend::PP;
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 };
407 # To save memory, the below lines are read only when XS backend is used.
417 # Helper classes for Backend Module (XS)
420 package JSON::Backend::XS;
422 use constant INDENT_LENGTH_FLAG => 15 << 12;
424 use constant UNSUPPORTED_ENCODE_FLAG => {
425 ESCAPE_SLASH => 0x00000010,
426 ALLOW_BIGNUM => 0x00000020,
427 AS_NONBLESSED => 0x00000040,
428 EXPANDED => 0x10000000, # for developer's
431 use constant UNSUPPORTED_DECODE_FLAG => {
433 ALLOW_BIGNUM => 0x00000002,
434 ALLOW_BAREKEY => 0x00000004,
435 ALLOW_SINGLEQUOTE => 0x00000008,
436 EXPANDED => 0x20000000, # for developer's
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 };
452 my ($class, @methods) = @_;
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;
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;
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;
469 push @JSON::Backend::XS::Supportable::ISA, 'JSON';
471 my $pkg = 'JSON::Backend::XS::Supportable';
474 my $proto = JSON::XS->new; $$proto = 0;
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);
486 $pkg->_make_unsupported_method($method => $type);
489 push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
490 push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
492 $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
501 # Helper classes for XS
504 package JSON::Backend::XS::Supportable;
506 $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
508 sub _make_unsupported_method {
509 my ($pkg, $method, $type) = @_;
514 *{"$pkg\::$method"} = sub {
516 if (defined $_[1] ? $_[1] : 1) {
525 *{"$pkg\::get_$method"} = sub {
526 ${$_[0]} & $type ? 1 : '';
533 JSON::_load_pp( $_INSTALL_ONLY );
536 my $pp = JSON::PP->new;
537 my $prop = $_[0]->property;
539 for my $name (keys %$prop) {
540 $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
543 my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
544 : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
545 my $flags = ${$_[0]} || 0;
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);
554 $pp->indent_length( $_[0]->get_indent_length );
559 sub _encode { # using with PP encode
561 _set_for_pp('encode' => @_)->encode($_[1]);
564 $_[0]->_original_encode( $_[1] );
569 sub _decode { # if unsupported-flag is set, use PP
571 _set_for_pp('decode' => @_)->decode($_[1]);
574 $_[0]->_original_decode( $_[1] );
579 sub decode_prefix { # if unsupported-flag is set, use PP
580 _set_for_pp('decode' => @_)->decode_prefix($_[1]);
586 _set_for_pp('decode' => @_)->incr_parse($_[1]);
589 $_[0]->_original_incr_parse( $_[1] );
594 sub get_indent_length {
602 if (!defined $length or $length > 15 or $length < 0) {
603 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
608 ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
610 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
622 JSON - JSON (JavaScript Object Notation) encoder/decoder
626 use JSON; # imports encode_json, decode_json, to_json and from_json.
628 # simple and fast interfaces (expect/generate UTF-8)
630 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
631 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
635 $json = JSON->new->allow_nonref;
637 $json_text = $json->encode( $perl_scalar );
638 $perl_scalar = $json->decode( $json_text );
640 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
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.
645 use JSON -support_by_pp;
647 # option-acceptable interfaces (expect/generate UNICODE by default)
649 $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
650 $perl_scalar = from_json( $json_text, { utf8 => 1 } );
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.
660 This version is compatible with JSON::XS B<2.34> and later.
665 JSON::PP was earlier included in the C<JSON> distribution, but
666 has since Perl 5.14 been a core module. For this reason,
667 L<JSON::PP> was removed from the JSON distribution and can now
668 be found also in the Perl5 repository at
672 =item * L<http://perl5.git.perl.org/perl.git>
676 (The newest JSON::PP version still exists in CPAN.)
678 Instead, the C<JSON> distribution will include JSON::backportPP
679 for backwards computability. JSON.pm should thus work as it did
684 ************************** CAUTION ********************************
685 * This is 'JSON module version 2' and there are many differences *
687 * Please check your applications using old version. *
688 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
689 *******************************************************************
691 JSON (JavaScript Object Notation) is a simple data format.
692 See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
694 This module converts Perl data structures to JSON and vice versa using either
695 L<JSON::XS> or L<JSON::PP>.
697 JSON::XS is the fastest and most proper JSON module on CPAN which must be
698 compiled and installed in your environment.
699 JSON::PP is a pure-Perl module which is bundled in this distribution and
700 has a strong compatibility to JSON::XS.
702 This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
703 So its features completely depend on JSON::XS or JSON::PP.
705 See to L<BACKEND MODULE DECISION>.
707 To distinguish the module name 'JSON' and the format type JSON,
708 the former is quoted by CE<lt>E<gt> (its results vary with your using media),
709 and the latter is left just as it is.
711 Module name : C<JSON>
719 =item * correct unicode handling
721 This module (i.e. backend modules) knows how to handle Unicode, documents
722 how and when it does so, and even documents what "correct" means.
724 Even though there are limitations, this feature is available since Perl version 5.6.
726 JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
727 C<JSON> should call JSON::PP as the backend which can be used since Perl 5.005.
729 With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
730 JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
731 See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
733 See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
734 and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
737 =item * round-trip integrity
739 When you serialise a perl data structure using only data types supported
740 by JSON and Perl, the deserialised data structure is identical on the Perl
741 level. (e.g. the string "2.0" doesn't suddenly become "2" just because
742 it looks like a number). There I<are> minor exceptions to this, read the
743 L</MAPPING> section below to learn about those.
746 =item * strict checking of JSON correctness
748 There is no guessing, no generating of illegal JSON texts by default,
749 and only JSON is accepted as input by default (the latter is a security
752 See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
756 This module returns a JSON::XS object itself if available.
757 Compared to other JSON modules and other serialisers such as Storable,
758 JSON::XS usually compares favorably in terms of speed, too.
760 If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
761 it is very slow as pure-Perl.
763 =item * simple to use
765 This module has both a simple functional interface as well as an
766 object oriented interface interface.
768 =item * reasonably versatile output formats
770 You 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
772 is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
773 format (for when you want to read that stuff). Or you can combine those features
774 in whatever way you like.
778 =head1 FUNCTIONAL INTERFACE
780 Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
781 C<to_json> and C<from_json> are additional functions.
785 $json_text = encode_json $perl_scalar
787 Converts the given Perl data structure to a UTF-8 encoded, binary string.
789 This function call is functionally identical to:
791 $json_text = JSON->new->utf8->encode($perl_scalar)
795 $perl_scalar = decode_json $json_text
797 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
798 to parse that as an UTF-8 encoded JSON text, returning the resulting
801 This function call is functionally identical to:
803 $perl_scalar = JSON->new->utf8->decode($json_text)
808 $json_text = to_json($perl_scalar)
810 Converts the given Perl data structure to a json string.
812 This function call is functionally identical to:
814 $json_text = JSON->new->encode($perl_scalar)
816 Takes a hash reference as the second.
818 $json_text = to_json($perl_scalar, $flag_hashref)
822 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
826 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
828 If you want to write a modern perl code which communicates to outer world,
829 you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
833 $perl_scalar = from_json($json_text)
835 The opposite of C<to_json>: expects a json string and tries
836 to parse it, returning the resulting reference.
838 This function call is functionally identical to:
840 $perl_scalar = JSON->decode($json_text)
842 Takes a hash reference as the second.
844 $perl_scalar = from_json($json_text, $flag_hashref)
848 $perl_scalar = from_json($json_text, {utf8 => 1})
852 $perl_scalar = JSON->new->utf8(1)->decode($json_text)
854 If you want to write a modern perl code which communicates to outer world,
855 you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
859 $is_boolean = JSON::is_bool($scalar)
861 Returns true if the passed scalar represents either JSON::true or
862 JSON::false, two constants that act like C<1> and C<0> respectively
863 and are also used to represent JSON C<true> and C<false> in Perl strings.
867 Returns JSON true value which is blessed object.
868 It C<isa> JSON::Boolean object.
872 Returns JSON false value which is blessed object.
873 It C<isa> JSON::Boolean object.
879 See L<MAPPING>, below, for more information on how JSON values are mapped to
882 =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
884 This section supposes that your perl version is 5.8 or later.
886 If you know a JSON text from an outer world - a network, a file content, and so on,
887 is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
888 with C<utf8> enable. And the decoded result will contain UNICODE characters.
891 my $json = JSON->new->utf8;
892 my $json_text = CGI->new->param( 'json_data' );
893 my $perl_scalar = $json->decode( $json_text );
897 open( my $fh, '<', 'json.data' );
899 $perl_scalar = decode_json( $json_text );
901 If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
905 open( my $fh, '<', 'json.data' );
906 my $encoding = 'cp932';
907 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
909 # or you can write the below code.
911 # open( my $fh, "<:encoding($encoding)", 'json.data' );
912 # $unicode_json_text = <$fh>;
914 In this case, C<$unicode_json_text> is of course UNICODE string.
915 So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
916 Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
918 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
920 $perl_scalar = from_json( $unicode_json_text );
922 Or C<encode 'utf8'> and C<decode_json>:
924 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
925 # this way is not efficient.
927 And now, you want to convert your C<$perl_scalar> into JSON data and
928 send it to an outer world - a network or a file content, and so on.
930 Your data usually contains UNICODE strings and you want the converted data to be encoded
931 in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
933 print encode_json( $perl_scalar ); # to a network? file? or display?
935 print $json->utf8->encode( $perl_scalar );
937 If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
938 for some reason, then its characters are regarded as B<latin1> for perl
939 (because it does not concern with your $encoding).
940 You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
941 Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
942 Note that the resulted text is a UNICODE string but no problem to print it.
944 # $perl_scalar contains $encoding encoded string values
945 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
947 $unicode_json_text = to_json( $perl_scalar );
948 # $unicode_json_text consists of characters less than 0x100
949 print $unicode_json_text;
951 Or C<decode $encoding> all string values and C<encode_json>:
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 );
957 This method is a proper way but probably not efficient.
959 See to L<Encode>, L<perluniintro>.
962 =head1 COMMON OBJECT-ORIENTED INTERFACE
968 Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
969 that can be used to de/encode JSON strings.
971 All boolean flags described below are by default I<disabled>.
973 The mutators for flags all return the JSON object again and thus calls can
976 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
981 $json = $json->ascii([$enable])
983 $enabled = $json->get_ascii
985 If $enable is true (or missing), then the encode method will not generate characters outside
986 the code range 0..127. Any Unicode characters outside that range will be escaped using either
987 a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
989 If $enable is false, then the encode method will not escape Unicode characters unless
990 required by the JSON syntax or other flags. This results in a faster and more compact format.
992 This feature depends on the used Perl version and environment.
994 See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
996 JSON->new->ascii(1)->encode([chr 0x10401])
1001 $json = $json->latin1([$enable])
1003 $enabled = $json->get_latin1
1005 If $enable is true (or missing), then the encode method will encode the resulting JSON
1006 text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
1008 If $enable is false, then the encode method will not escape Unicode characters
1009 unless required by the JSON syntax or other flags.
1011 JSON->new->latin1->encode (["\x{89}\x{abc}"]
1012 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
1016 $json = $json->utf8([$enable])
1018 $enabled = $json->get_utf8
1020 If $enable is true (or missing), then the encode method will encode the JSON result
1021 into UTF-8, as required by many protocols, while the decode method expects to be handled
1022 an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
1023 characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
1025 In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
1026 encoding families, as described in RFC4627.
1028 If $enable is false, then the encode method will return the JSON string as a (non-encoded)
1029 Unicode 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.
1033 Example, output UTF-16BE-encoded JSON:
1036 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
1038 Example, decode UTF-32LE-encoded JSON:
1041 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
1043 See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
1048 $json = $json->pretty([$enable])
1050 This enables (or disables) all of the C<indent>, C<space_before> and
1051 C<space_after> (and in the future possibly more) flags in one call to
1052 generate the most readable (or most compact) form possible.
1056 $json->indent->space_before->space_after
1058 The indent space length is three and JSON::XS cannot change the indent
1063 $json = $json->indent([$enable])
1065 $enabled = $json->get_indent
1067 If C<$enable> is true (or missing), then the C<encode> method will use a multiline
1068 format as output, putting every array member or object/hash key-value pair
1069 into its own line, identifying them properly.
1071 If C<$enable> is false, no newlines or indenting will be produced, and the
1072 resulting JSON text is guaranteed not to contain any C<newlines>.
1074 This setting has no effect when decoding JSON texts.
1076 The indent space length is three.
1077 With JSON::PP, you can also access C<indent_length> to change indent space length.
1082 $json = $json->space_before([$enable])
1084 $enabled = $json->get_space_before
1086 If C<$enable> is true (or missing), then the C<encode> method will add an extra
1087 optional space before the C<:> separating keys from values in JSON objects.
1089 If C<$enable> is false, then the C<encode> method will not add any extra
1090 space at those places.
1092 This setting has no effect when decoding JSON texts.
1094 Example, space_before enabled, space_after and indent disabled:
1101 $json = $json->space_after([$enable])
1103 $enabled = $json->get_space_after
1105 If C<$enable> is true (or missing), then the C<encode> method will add an extra
1106 optional space after the C<:> separating keys from values in JSON objects
1107 and extra whitespace after the C<,> separating key-value pairs and array
1110 If C<$enable> is false, then the C<encode> method will not add any extra
1111 space at those places.
1113 This setting has no effect when decoding JSON texts.
1115 Example, space_before and indent disabled, space_after enabled:
1122 $json = $json->relaxed([$enable])
1124 $enabled = $json->get_relaxed
1126 If C<$enable> is true (or missing), then C<decode> will accept some
1127 extensions to normal JSON syntax (see below). C<encode> will not be
1128 affected in anyway. I<Be aware that this option makes you accept invalid
1129 JSON texts as if they were valid!>. I suggest only to use this option to
1130 parse application-specific files written by humans (configuration files,
1131 resource files etc.)
1133 If C<$enable> is false (the default), then C<decode> will only accept
1136 Currently accepted extensions are:
1140 =item * list items can have an end-comma
1142 JSON I<separates> array elements and key-value pairs with commas. This
1143 can be annoying if you write JSON texts manually and want to be able to
1144 quickly append elements, so this extension accepts comma at the end of
1145 such items not just between them:
1149 2, <- this comma not normally allowed
1153 "k2": "v2", <- this comma not normally allowed
1156 =item * shell-style '#'-comments
1158 Whenever JSON allows whitespace, shell-style comments are additionally
1159 allowed. They are terminated by the first carriage-return or line-feed
1160 character, after which more white-space and comments are allowed.
1163 1, # this comment not allowed in JSON
1164 # neither this one...
1172 $json = $json->canonical([$enable])
1174 $enabled = $json->get_canonical
1176 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
1177 by sorting their keys. This is adding a comparatively high overhead.
1179 If C<$enable> is false, then the C<encode> method will output key-value
1180 pairs in the order Perl stores them (which will likely change between runs
1181 of the same script).
1183 This option is useful if you want the same data structure to be encoded as
1184 the same JSON text (given the same overall settings). If it is disabled,
1185 the same hash might be encoded differently even if contains the same data,
1186 as key-value pairs have no inherent ordering in Perl.
1188 This setting has no effect when decoding JSON texts.
1192 $json = $json->allow_nonref([$enable])
1194 $enabled = $json->get_allow_nonref
1196 If C<$enable> is true (or missing), then the C<encode> method can convert a
1197 non-reference into its corresponding string, number or null JSON value,
1198 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
1199 values instead of croaking.
1201 If C<$enable> is false, then the C<encode> method will croak if it isn't
1202 passed an arrayref or hashref, as JSON texts must either be an object
1203 or array. Likewise, C<decode> will croak if given something that is not a
1204 JSON object or array.
1206 JSON->new->allow_nonref->encode ("Hello, World!")
1209 =head2 allow_unknown
1211 $json = $json->allow_unknown ([$enable])
1213 $enabled = $json->get_allow_unknown
1215 If $enable is true (or missing), then "encode" will *not* throw an
1216 exception when it encounters values it cannot represent in JSON (for
1217 example, filehandles) but instead will encode a JSON "null" value.
1218 Note that blessed objects are not included here and are handled
1219 separately by c<allow_nonref>.
1221 If $enable is false (the default), then "encode" will throw an
1222 exception when it encounters anything it cannot encode as JSON.
1224 This option does not affect "decode" in any way, and it is
1225 recommended to leave it off unless you know your communications
1228 =head2 allow_blessed
1230 $json = $json->allow_blessed([$enable])
1232 $enabled = $json->get_allow_blessed
1234 If C<$enable> is true (or missing), then the C<encode> method will not
1235 barf when it encounters a blessed reference. Instead, the value of the
1236 B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
1237 disabled or no C<TO_JSON> method found) or a representation of the
1238 object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
1239 encoded. Has no effect on C<decode>.
1241 If C<$enable> is false (the default), then C<encode> will throw an
1242 exception when it encounters a blessed object.
1245 =head2 convert_blessed
1247 $json = $json->convert_blessed([$enable])
1249 $enabled = $json->get_convert_blessed
1251 If C<$enable> is true (or missing), then C<encode>, upon encountering a
1252 blessed object, will check for the availability of the C<TO_JSON> method
1253 on the object's class. If found, it will be called in scalar context
1254 and the resulting scalar will be encoded instead of the object. If no
1255 C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
1258 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
1259 returns other blessed objects, those will be handled in the same
1260 way. 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
1262 methods called by the Perl core (== not by the user of the object) are
1263 usually in upper case letters and to avoid collisions with the C<to_json>
1266 This setting does not yet influence C<decode> in any way.
1268 If C<$enable> is false, then the C<allow_blessed> setting will decide what
1269 to do when a blessed object is found.
1273 =item convert_blessed_universally mode
1275 If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
1276 subroutine is defined as the below code:
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] } ]
1286 This will cause that C<encode> method converts simple blessed objects into
1287 JSON objects as non-blessed object.
1289 JSON -convert_blessed_universally;
1290 $json->allow_blessed->convert_blessed->encode( $blessed_object )
1292 This feature is experimental and may be removed in the future.
1296 =head2 filter_json_object
1298 $json = $json->filter_json_object([$coderef])
1300 When C<$coderef> is specified, it will be called from C<decode> each
1301 time it decodes a JSON object. The only argument passed to the coderef
1302 is a reference to the newly-created hash. If the code references returns
1303 a 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
1305 deserialised data structure. If it returns an empty list
1306 (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
1307 hash will be inserted. This setting can slow down decoding considerably.
1309 When C<$coderef> is omitted or undefined, any existing callback will
1310 be removed and C<decode> will not change the deserialised hash in any
1313 Example, convert all JSON objects into the integer 5:
1315 my $js = JSON->new->filter_json_object (sub { 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}');
1323 =head2 filter_json_single_key_object
1325 $json = $json->filter_json_single_key_object($key [=> $coderef])
1327 Works remotely similar to C<filter_json_object>, but is only called for
1328 JSON objects having a single key named C<$key>.
1330 This C<$coderef> is called before the one specified via
1331 C<filter_json_object>, if any. It gets passed the single value in the JSON
1332 object. If it returns a single value, it will be inserted into the data
1333 structure. If it returns nothing (not even C<undef> but the empty list),
1334 the callback from C<filter_json_object> will be called next, as if no
1335 single-key callback were specified.
1337 If C<$coderef> is omitted or undefined, the corresponding callback will be
1338 disabled. There can only ever be one callback for a given key.
1340 As this callback gets called less often then the C<filter_json_object>
1341 one, decoding speed will not usually suffer as much. Therefore, single-key
1342 objects make excellent targets to serialise Perl objects into, especially
1343 as single-key JSON objects are as close to the type-tagged value concept
1344 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
1345 support this in any way, so you need to make sure your data never looks
1346 like a serialised Perl hash.
1348 Typical names for the single object key are C<__class_whatever__>, or
1349 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
1350 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
1353 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
1354 into the corresponding C<< $WIDGET{<id>} >> object:
1356 # return whatever is in $WIDGET{5}:
1359 ->filter_json_single_key_object (__widget__ => sub {
1362 ->decode ('{"__widget__": 5')
1364 # this can be used with a TO_JSON method in some "widget" class
1365 # for serialisation to json:
1366 sub WidgetBase::TO_JSON {
1369 unless ($self->{id}) {
1370 $self->{id} = ..get..some..id..;
1371 $WIDGET{$self->{id}} = $self;
1374 { __widget__ => $self->{id} }
1380 $json = $json->shrink([$enable])
1382 $enabled = $json->get_shrink
1384 With JSON::XS, this flag resizes strings generated by either
1385 C<encode> or C<decode> to their minimum size possible. This can save
1386 memory when your JSON texts are either very very long or you have many
1387 short strings. It will also try to downgrade any strings to octet-form
1388 if possible: perl stores strings internally either in an encoding called
1389 UTF-X or in octet-form. The latter cannot store everything but uses less
1390 space in general (and some buggy Perl or C code might even rely on that
1391 internal representation being used).
1393 With JSON::PP, it is noop about resizing strings but tries
1394 C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
1396 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
1400 $json = $json->max_depth([$maximum_nesting_depth])
1402 $max_depth = $json->get_max_depth
1404 Sets the maximum nesting level (default C<512>) accepted while encoding
1405 or decoding. If a higher nesting level is detected in JSON text or a Perl
1406 data structure, then the encoder and decoder will stop and croak at that
1409 Nesting level is defined by number of hash- or arrayrefs that the encoder
1410 needs to traverse to reach a given point or the number of C<{> or C<[>
1411 characters without their matching closing parenthesis crossed to reach a
1412 given character in a string.
1414 If no argument is given, the highest possible setting will be used, which
1417 Note that nesting is implemented by recursion in C. The default value has
1418 been chosen to be as large as typical operating systems allow without
1419 crashing. (JSON::XS)
1421 With JSON::PP as the backend, when a large value (100 or more) was set and
1422 it de/encodes a deep nested object/text, it may raise a warning
1423 'Deep recursion on subroutine' at the perl runtime phase.
1425 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1429 $json = $json->max_size([$maximum_string_size])
1431 $max_size = $json->get_max_size
1433 Set the maximum length a JSON text may have (in bytes) where decoding is
1434 being attempted. The default is C<0>, meaning no limit. When C<decode>
1435 is called on a string that is longer then this many bytes, it will not
1436 attempt to decode the string but throw an exception. This setting has no
1437 effect on C<encode> (yet).
1439 If no argument is given, the limit check will be deactivated (same as when
1442 See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
1446 $json_text = $json->encode($perl_scalar)
1448 Converts the given Perl data structure (a simple scalar or a reference
1449 to a hash or array) to its JSON representation. Simple scalars will be
1450 converted into JSON string or number sequences, while references to arrays
1451 become JSON arrays and references to hashes become JSON objects. Undefined
1452 Perl values (e.g. C<undef>) become JSON C<null> values.
1453 References to the integers C<0> and C<1> are converted into C<true> and C<false>.
1457 $perl_scalar = $json->decode($json_text)
1459 The opposite of C<encode>: expects a JSON text and tries to parse it,
1460 returning the resulting simple scalar or reference. Croaks on error.
1462 JSON numbers and strings become simple Perl scalars. JSON arrays become
1463 Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
1464 C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
1465 C<null> becomes C<undef>.
1467 =head2 decode_prefix
1469 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
1471 This works like the C<decode> method, but instead of raising an exception
1472 when there is trailing garbage after the first JSON object, it will
1473 silently stop parsing there and return the number of characters consumed
1476 JSON->new->decode_prefix ("[1] the tail")
1479 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
1483 $boolean = $json->property($property_name)
1485 Returns a boolean value about above some properties.
1487 The available properties are C<ascii>, C<latin1>, C<utf8>,
1488 C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
1489 C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
1490 C<shrink>, C<max_depth> and C<max_size>.
1492 $boolean = $json->property('utf8');
1495 $boolean = $json->property('utf8');
1498 Sets the property with a given boolean value.
1500 $json = $json->property($property_name => $boolean);
1502 With no argument, it returns all the above properties as a hash reference.
1504 $flag_hashref = $json->property();
1506 =head1 INCREMENTAL PARSING
1508 Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
1510 In some cases, there is the need for incremental parsing of JSON texts.
1511 This module does allow you to parse a JSON stream incrementally.
1512 It does so by accumulating text until it has a full JSON object, which
1513 it then can decode. This process is similar to using C<decode_prefix>
1514 to see if a full JSON object is available, but is much more efficient
1515 (and can be implemented with a minimum of method calls).
1517 The backend module will only attempt to parse the JSON text once it is sure it
1518 has enough text to get a decisive result, using a very simple but
1519 truly incremental parser. This means that it sometimes won't stop as
1520 early as the full parser, for example, it doesn't detect parenthesis
1521 mismatches. The only thing it guarantees is that it starts decoding as
1522 soon as a syntactically valid JSON text has been seen. This means you need
1523 to set resource limits (e.g. C<max_size>) to ensure the parser will stop
1524 parsing in the presence if syntax errors.
1526 The following methods implement this incremental parser.
1530 $json->incr_parse( [$string] ) # void context
1532 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
1534 @obj_or_empty = $json->incr_parse( [$string] ) # list context
1536 This is the central parsing function. It can both append new text and
1537 extract objects from the stream accumulated so far (both of these
1538 functions are optional).
1540 If C<$string> is given, then this string is appended to the already
1541 existing JSON fragment stored in the C<$json> object.
1543 After that, if the function is called in void context, it will simply
1544 return without doing anything further. This can be used to add more text
1545 in as many chunks as you want.
1547 If the method is called in scalar context, then it will try to extract
1548 exactly I<one> JSON object. If that is successful, it will return this
1549 object, otherwise it will return C<undef>. If there is a parse error,
1550 this method will croak just as C<decode> would do (one can then use
1551 C<incr_skip> to skip the erroneous part). This is the most common way of
1554 And finally, in list context, it will try to extract as many objects
1555 from the stream as it can find and return them, or the empty list
1556 otherwise. For this to work, there must be no separators between the JSON
1557 objects or arrays, instead they must be concatenated back-to-back. If
1558 an error occurs, an exception will be raised as in the scalar context
1559 case. Note that in this case, any previously-parsed JSON texts will be
1562 Example: Parse some JSON arrays/objects in a given string and return them.
1564 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
1568 $lvalue_string = $json->incr_text
1570 This method returns the currently stored JSON fragment as an lvalue, that
1571 is, you can manipulate it. This I<only> works when a preceding call to
1572 C<incr_parse> in I<scalar context> successfully returned an object. Under
1573 all other circumstances you must not call this function (I mean it.
1574 although in simple tests it might actually work, it I<will> fail under
1575 real world conditions). As a special exception, you can also call this
1576 method before having parsed anything.
1578 This function is useful in two cases: a) finding the trailing text after a
1579 JSON object or b) parsing multiple JSON objects separated by non-JSON text
1582 $json->incr_text =~ s/\s*,\s*//;
1584 In Perl 5.005, C<lvalue> attribute is not available.
1585 You must write codes like the below:
1587 $string = $json->incr_text;
1588 $string =~ s/\s*,\s*//;
1589 $json->incr_text( $string );
1595 This will reset the state of the incremental parser and will remove the
1596 parsed text from the input buffer. This is useful after C<incr_parse>
1597 died, in which case the input buffer and incremental parser state is left
1598 unchanged, to skip the text parsed so far and to reset the parse state.
1604 This completely resets the incremental parser, that is, after this call,
1605 it will be as if the parser had never parsed anything.
1607 This is useful if you want to repeatedly parse JSON objects and want to
1608 ignore any trailing data, which means you have to reset the parser after
1609 each successful decode.
1611 See to L<JSON::XS/INCREMENTAL PARSING> for examples.
1614 =head1 JSON::PP SUPPORT METHODS
1616 The below methods are JSON::PP own methods, so when C<JSON> works
1617 with JSON::PP (i.e. the created object is a JSON::PP object), available.
1618 See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
1620 If you use C<JSON> with additional C<-support_by_pp>, some methods
1621 are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
1623 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
1625 use JSON -support_by_pp;
1627 my $json = JSON->new;
1628 $json->allow_nonref->escape_slash->encode("/");
1630 # functional interfaces too.
1631 print to_json(["/"], {escape_slash => 1});
1632 print from_json('["foo"]', {utf8 => 1});
1634 If you do not want to all functions but C<-support_by_pp>,
1637 use JSON -support_by_pp, -no_export;
1638 # functional interfaces are not exported.
1640 =head2 allow_singlequote
1642 $json = $json->allow_singlequote([$enable])
1644 If C<$enable> is true (or missing), then C<decode> will accept
1645 any JSON strings quoted by single quotations that are invalid JSON
1648 $json->allow_singlequote->decode({"foo":'bar'});
1649 $json->allow_singlequote->decode({'foo':"bar"});
1650 $json->allow_singlequote->decode({'foo':'bar'});
1652 As same as the C<relaxed> option, this option may be used to parse
1653 application-specific files written by humans.
1655 =head2 allow_barekey
1657 $json = $json->allow_barekey([$enable])
1659 If C<$enable> is true (or missing), then C<decode> will accept
1660 bare keys of JSON object that are invalid JSON format.
1662 As same as the C<relaxed> option, this option may be used to parse
1663 application-specific files written by humans.
1665 $json->allow_barekey->decode('{foo:"bar"}');
1669 $json = $json->allow_bignum([$enable])
1671 If C<$enable> is true (or missing), then C<decode> will convert
1672 the big integer Perl cannot handle as integer into a L<Math::BigInt>
1673 object and convert a floating number (any) into a L<Math::BigFloat>.
1675 On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1676 objects into JSON numbers with C<allow_blessed> enable.
1678 $json->allow_nonref->allow_blessed->allow_bignum;
1679 $bigfloat = $json->decode('2.000000000000000000000000001');
1680 print $json->encode($bigfloat);
1681 # => 2.000000000000000000000000001
1683 See to L<MAPPING> about the conversion of JSON number.
1687 $json = $json->loose([$enable])
1689 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
1690 and the module doesn't allow to C<decode> to these (except for \x2f).
1691 If C<$enable> is true (or missing), then C<decode> will accept these
1694 $json->loose->decode(qq|["abc
1697 See to L<JSON::PP/JSON::PP OWN METHODS>.
1701 $json = $json->escape_slash([$enable])
1703 According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
1704 JSON backend modules encode strings without escaping slash.
1706 If C<$enable> is true (or missing), then C<encode> will escape slashes.
1708 =head2 indent_length
1710 $json = $json->indent_length($length)
1712 With JSON::XS, The indent space length is 3 and cannot be changed.
1713 With JSON::PP, it sets the indent space length with the given $length.
1714 The default is 3. The acceptable range is 0 to 15.
1718 $json = $json->sort_by($function_name)
1719 $json = $json->sort_by($subroutine_ref)
1721 If $function_name or $subroutine_ref are set, its sort routine are used.
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}|);
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}|);
1729 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
1731 As the sorting routine runs in the JSON::PP scope, the given
1732 subroutine name and the special variables C<$a>, C<$b> will begin
1735 If $integer is set, then the effect is same as C<canonical> on.
1737 See to L<JSON::PP/JSON::PP OWN METHODS>.
1741 This section is copied from JSON::XS and modified to C<JSON>.
1742 JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
1744 See to L<JSON::XS/MAPPING>.
1752 A JSON object becomes a reference to a hash in Perl. No ordering of object
1753 keys is preserved (JSON does not preserver object key ordering itself).
1757 A JSON array becomes a reference to an array in Perl.
1761 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1762 are represented by the same codepoints in the Perl string, so no manual
1763 decoding is necessary.
1767 A JSON number becomes either an integer, numeric (floating point) or
1768 string scalar in perl, depending on its range and any fractional parts. On
1769 the Perl level, there is no difference between those as Perl handles all
1770 the conversion details, but an integer may take slightly less memory and
1771 might represent more values exactly than floating point numbers.
1773 If the number consists of digits only, C<JSON> will try to represent
1774 it as an integer value. If that fails, it will try to represent it as
1775 a numeric (floating point) value if that is possible without loss of
1776 precision. Otherwise it will preserve the number as a string value (in
1777 which case you lose roundtripping ability, as the JSON number will be
1778 re-encoded to a JSON string).
1780 Numbers containing a fractional or exponential part will always be
1781 represented as numeric (floating point) values, possibly at a loss of
1782 precision (in which case you might lose perfect roundtripping ability, but
1783 the JSON number will still be re-encoded as a JSON number).
1785 Note that precision is not accuracy - binary floating point values cannot
1786 represent most decimal fractions exactly, and when converting from and to
1787 floating point, C<JSON> only guarantees precision up to but not including
1788 the least significant bit.
1790 If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
1791 and the numeric can be optionally converted into L<Math::BigInt> and
1792 L<Math::BigFloat> objects.
1796 These JSON atoms become C<JSON::true> and C<JSON::false>,
1797 respectively. They are overloaded to act almost exactly like the numbers
1798 C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
1799 the C<JSON::is_bool> function.
1801 If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
1802 they represent as C<true> and C<false> respectively.
1804 print JSON::true . "\n";
1806 print JSON::true + 1;
1809 ok(JSON::true eq 'true');
1810 ok(JSON::true eq '1');
1811 ok(JSON::true == 1);
1813 C<JSON> will install these missing overloading features to the backend modules.
1818 A JSON null atom becomes C<undef> in Perl.
1820 C<JSON::null> returns C<undef>.
1827 The mapping from Perl to JSON is slightly more difficult, as Perl is a
1828 truly typeless language, so we can only guess which JSON type is meant by
1833 =item hash references
1835 Perl hash references become JSON objects. As there is no inherent ordering
1836 in hash keys (or JSON objects), they will usually be encoded in a
1837 pseudo-random order that can change between runs of the same program but
1838 stays generally the same within a single run of a program. C<JSON>
1839 optionally sort the hash keys (determined by the I<canonical> flag), so
1840 the same data structure will serialise to the same JSON text (given same
1841 settings and version of JSON::XS), but this incurs a runtime overhead
1842 and is only rarely useful, e.g. when you want to compare some JSON text
1843 against another for equality.
1845 In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
1848 =item array references
1850 Perl array references become JSON arrays.
1852 =item other references
1854 Other unblessed references are generally not allowed and will cause an
1855 exception to be thrown, except for references to the integers C<0> and
1856 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1857 also use C<JSON::false> and C<JSON::true> to improve readability.
1859 to_json [\0,JSON::true] # yields [false,true]
1861 =item JSON::true, JSON::false, JSON::null
1863 These special values become JSON true and JSON false values,
1864 respectively. You can also use C<\1> and C<\0> directly if you want.
1866 JSON::null returns C<undef>.
1868 =item blessed objects
1870 Blessed objects are not directly representable in JSON. See the
1871 C<allow_blessed> and C<convert_blessed> methods on various options on
1872 how to deal with this: basically, you can choose between throwing an
1873 exception, encoding the reference as if it weren't blessed, or provide
1874 your own serialiser method.
1876 With C<convert_blessed_universally> mode, C<encode> converts blessed
1877 hash references or blessed array references (contains other blessed references)
1878 into JSON members and arrays.
1880 use JSON -convert_blessed_universally;
1881 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
1883 See to L<convert_blessed>.
1885 =item simple scalars
1887 Simple Perl scalars (any scalar that is not a reference) are the most
1888 difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
1889 JSON C<null> values, scalars that have last been used in a string context
1890 before encoding as JSON strings, and anything else as number value:
1893 encode_json [2] # yields [2]
1894 encode_json [-3.0e17] # yields [-3e+17]
1895 my $value = 5; encode_json [$value] # yields [5]
1897 # used as string, so dump as string
1899 encode_json [$value] # yields ["5"]
1901 # undef becomes null
1902 encode_json [undef] # yields [null]
1904 You can force the type to be a string by stringifying it:
1906 my $x = 3.1; # some variable containing a number
1908 $x .= ""; # another, more awkward way to stringify
1909 print $x; # perl does it for you, too, quite often
1911 You can force the type to be a number by numifying it:
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.
1917 You can not currently force the type in other, less obscure, ways.
1919 Note that numerical precision has the same meaning as under Perl (so
1920 binary to decimal conversion follows the same rules as in Perl, which
1921 can differ to other languages). Also, your perl interpreter might expose
1922 extensions to the floating point numbers of your platform, such as
1923 infinities or NaN's - these cannot be represented in JSON, and it is an
1924 error to pass those in.
1928 If the backend is JSON::PP and C<allow_bignum> is enable,
1929 C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1930 objects into JSON numbers.
1935 =head1 JSON and ECMAscript
1937 See to L<JSON::XS/JSON and ECMAscript>.
1939 =head1 JSON and YAML
1941 JSON is not a subset of YAML.
1942 See to L<JSON::XS/JSON and YAML>.
1945 =head1 BACKEND MODULE DECISION
1947 When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
1948 C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
1950 The C<JSON> constructor method returns an object inherited from the backend module,
1951 and JSON::XS object is a blessed scalar reference while JSON::PP is a blessed hash
1954 So, your program should not depend on the backend module, especially
1955 returned objects should not be modified.
1957 my $json = JSON->new; # XS or PP?
1958 $json->{stash} = 'this is xs object'; # this code may raise an error!
1960 To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
1962 JSON->backend; # 'JSON::XS' or 'JSON::PP'
1964 JSON->backend->is_pp: # 0 or 1
1966 JSON->backend->is_xs: # 1 or 0
1968 $json->is_xs; # 1 or 0
1970 $json->is_pp; # 0 or 1
1973 If you set an environment variable C<PERL_JSON_BACKEND>, the calling action will be changed.
1977 =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
1981 =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
1983 (The default) Use compiled JSON::XS if it is properly compiled & installed,
1984 otherwise use JSON::PP.
1986 =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
1988 Always use compiled JSON::XS, die if it isn't properly compiled & installed.
1990 =item PERL_JSON_BACKEND = 'JSON::backportPP'
1992 Always use JSON::backportPP.
1993 JSON::backportPP is JSON::PP back port module.
1994 C<JSON> includes JSON::backportPP instead of JSON::PP.
1998 These ideas come from L<DBI::PurePerl> mechanism.
2002 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
2003 use JSON; # always uses JSON::PP
2005 In future, it may be able to specify another module.
2007 =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
2009 Many methods are available with either JSON::XS or JSON::PP and
2010 when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unsupported)
2011 method is called, it will C<warn> and be noop.
2013 But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
2014 it makes a part of those unsupported methods available.
2015 This feature is achieved by using JSON::PP in C<de/encode>.
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("/");
2022 At this time, the returned object is a C<JSON::Backend::XS::Supportable>
2023 object (re-blessed XS object), and by checking JSON::XS unsupported flags
2024 in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
2025 C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
2027 When any unsupported methods are not enable, C<XS de/encode> will be
2028 used as is. The switch is achieved by changing the symbolic tables.
2030 C<-support_by_pp> is effective only when the backend module is JSON::XS
2031 and it makes the de/encoding speed down a bit.
2033 See to L<JSON::PP SUPPORT METHODS>.
2035 =head1 INCOMPATIBLE CHANGES TO OLD VERSION
2037 There are big incompatibility between new version (2.00) and old (1.xx).
2038 If you use old C<JSON> 1.xx in your code, please check it.
2040 See to L<Transition ways from 1.xx to 2.xx.>
2044 =item jsonToObj and objToJson are obsoleted.
2046 Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
2047 (but not yet deleted from the source).
2048 If you use these functions in your code, please replace them
2049 with C<from_json> and C<to_json>.
2052 =item Global variables are no longer available.
2054 C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
2055 - are not available any longer.
2056 Instead, various features can be used through object methods.
2059 =item Package JSON::Converter and JSON::Parser are deleted.
2061 Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
2063 =item Package JSON::NotString is deleted.
2065 There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
2066 and numbers. It was deleted and replaced by C<JSON::Boolean>.
2068 C<JSON::Boolean> represents C<true> and C<false>.
2070 C<JSON::Boolean> does not represent C<null>.
2072 C<JSON::null> returns C<undef>.
2074 C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
2075 to L<JSON::Boolean>.
2077 =item function JSON::Number is obsoleted.
2079 C<JSON::Number> is now needless because JSON::XS and JSON::PP have
2080 round-trip integrity.
2082 =item JSONRPC modules are deleted.
2084 Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
2085 and C<Apache::JSONRPC > are deleted in this distribution.
2086 Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
2090 =head2 Transition ways from 1.xx to 2.xx.
2092 You should set C<suport_by_pp> mode firstly, because
2093 it is always successful for the below codes even with JSON::XS.
2095 use JSON -support_by_pp;
2099 =item Exported jsonToObj (simple)
2101 from_json($json_text);
2103 =item Exported objToJson (simple)
2105 to_json($perl_scalar);
2107 =item Exported jsonToObj (advanced)
2109 $flags = {allow_barekey => 1, allow_singlequote => 1};
2110 from_json($json_text, $flags);
2115 $JSON::QuotApos = 1;
2116 jsonToObj($json_text);
2118 =item Exported objToJson (advanced)
2120 $flags = {allow_blessed => 1, allow_barekey => 1};
2121 to_json($perl_scalar, $flags);
2126 objToJson($perl_scalar);
2128 =item jsonToObj as object method
2130 $json->decode($json_text);
2132 =item objToJson as object method
2134 $json->encode($perl_scalar);
2136 =item new method with parameters
2138 The C<new> method in 2.x takes any parameters no longer.
2139 You can set parameters instead;
2141 $json = JSON->new->pretty;
2143 =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
2145 If C<indent> is enable, that means C<$JSON::Pretty> flag set. And
2146 C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
2149 $json->indent->space_before->space_after;
2155 To change indent length, use C<indent_length>.
2157 (Only with JSON::PP, if C<-support_by_pp> is not used.)
2159 $json->pretty->indent_length(2)->encode($perl_scalar);
2161 =item $JSON::BareKey
2163 (Only with JSON::PP, if C<-support_by_pp> is not used.)
2165 $json->allow_barekey->decode($json_text)
2167 =item $JSON::ConvBlessed
2169 use C<-convert_blessed_universally>. See to L<convert_blessed>.
2171 =item $JSON::QuotApos
2173 (Only with JSON::PP, if C<-support_by_pp> is not used.)
2175 $json->allow_singlequote->decode($json_text)
2177 =item $JSON::SingleQuote
2179 Disable. C<JSON> does not make such a invalid JSON string any longer.
2181 =item $JSON::KeySort
2183 $json->canonical->encode($perl_scalar)
2185 This is the ascii sort.
2187 If you want to use with your own sort routine, check the C<sort_by> method.
2189 (Only with JSON::PP, even if C<-support_by_pp> is used currently.)
2191 $json->sort_by($sort_routine_ref)->encode($perl_scalar)
2193 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
2195 Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
2197 =item $JSON::SkipInvalid
2199 $json->allow_unknown
2201 =item $JSON::AUTOCONVERT
2203 Needless. C<JSON> backend modules have the round-trip integrity.
2207 Needless because C<JSON> (JSON::XS/JSON::PP) sets
2208 the UTF8 flag on properly.
2210 # With UTF8-flagged strings
2212 $json->allow_nonref;
2213 $str = chr(1000); # UTF8-flagged
2215 $json_text = $json->utf8(0)->encode($str);
2216 utf8::is_utf8($json_text);
2218 $json_text = $json->utf8(1)->encode($str);
2219 utf8::is_utf8($json_text);
2222 $str = '"' . chr(1000) . '"'; # UTF8-flagged
2224 $perl_scalar = $json->utf8(0)->decode($str);
2225 utf8::is_utf8($perl_scalar);
2227 $perl_scalar = $json->utf8(1)->decode($str);
2228 # died because of 'Wide character in subroutine'
2230 See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
2232 =item $JSON::UnMapping
2234 Disable. See to L<MAPPING>.
2236 =item $JSON::SelfConvert
2238 This option was deleted.
2239 Instead of it, if a given blessed object has the C<TO_JSON> method,
2240 C<TO_JSON> will be executed with C<convert_blessed>.
2242 $json->convert_blessed->encode($blessed_hashref_or_arrayref)
2243 # if need, call allow_blessed
2245 Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
2253 =item example programs
2259 No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
2264 Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
2269 Most of the document is copied and modified from JSON::XS doc.
2271 L<JSON::XS>, L<JSON::PP>
2273 C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
2277 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
2279 JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
2281 The release of this new version owes to the courtesy of Marc Lehmann.
2284 =head1 COPYRIGHT AND LICENSE
2286 Copyright 2005-2013 by Makamaka Hannyaharamitu
2288 This library is free software; you can redistribute it and/or modify
2289 it under the same terms as Perl itself.