7 @JSON::EXPORT
= qw(from_json to_json jsonToObj objToJson encode_json decode_json);
10 $JSON::VERSION
= '2.53';
11 $JSON::DEBUG
= 0 unless (defined $JSON::DEBUG
);
12 $JSON::DEBUG
= $ENV{ PERL_JSON_DEBUG
} if exists $ENV{ PERL_JSON_DEBUG
};
15 my $Module_XS = 'JSON::XS';
16 my $Module_PP = 'JSON::PP';
17 my $Module_bp = 'JSON::backportPP'; # included in JSON distribution
18 my $PP_Version = '2.27200';
19 my $XS_Version = '2.27';
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.";
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.";
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 redifines 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
$@
; }
376 # Helper classes for Backend Module (PP)
379 package JSON
::Backend
::PP
;
383 no strict
qw(refs); # this routine may be called after JSON::Backend::XS init was called.
384 *{"JSON::decode_json"} = \
&{"JSON::PP::decode_json"};
385 *{"JSON::encode_json"} = \
&{"JSON::PP::encode_json"};
386 *{"JSON::PP::is_xs"} = sub { 0 };
387 *{"JSON::PP::is_pp"} = sub { 1 };
392 # To save memory, the below lines are read only when XS backend is used.
402 # Helper classes for Backend Module (XS)
405 package JSON
::Backend
::XS
;
407 use constant INDENT_LENGTH_FLAG
=> 15 << 12;
409 use constant UNSUPPORTED_ENCODE_FLAG
=> {
410 ESCAPE_SLASH
=> 0x00000010,
411 ALLOW_BIGNUM
=> 0x00000020,
412 AS_NONBLESSED
=> 0x00000040,
413 EXPANDED
=> 0x10000000, # for developer's
416 use constant UNSUPPORTED_DECODE_FLAG
=> {
418 ALLOW_BIGNUM
=> 0x00000002,
419 ALLOW_BAREKEY
=> 0x00000004,
420 ALLOW_SINGLEQUOTE
=> 0x00000008,
421 EXPANDED
=> 0x20000000, # for developer's
428 *{"JSON::decode_json"} = \
&{"JSON::XS::decode_json"};
429 *{"JSON::encode_json"} = \
&{"JSON::XS::encode_json"};
430 *{"JSON::XS::is_xs"} = sub { 1 };
431 *{"JSON::XS::is_pp"} = sub { 0 };
437 my ($class, @methods) = @_;
442 my $JSON_XS_encode_orignal = \
&JSON
::XS
::encode
;
443 my $JSON_XS_decode_orignal = \
&JSON
::XS
::decode
;
444 my $JSON_XS_incr_parse_orignal = \
&JSON
::XS
::incr_parse
;
446 *JSON
::XS
::decode
= \
&JSON
::Backend
::XS
::Supportable
::_decode
;
447 *JSON
::XS
::encode
= \
&JSON
::Backend
::XS
::Supportable
::_encode
;
448 *JSON
::XS
::incr_parse
= \
&JSON
::Backend
::XS
::Supportable
::_incr_parse
;
450 *{JSON
::XS
::_original_decode
} = $JSON_XS_decode_orignal;
451 *{JSON
::XS
::_original_encode
} = $JSON_XS_encode_orignal;
452 *{JSON
::XS
::_original_incr_parse
} = $JSON_XS_incr_parse_orignal;
454 push @JSON::Backend
::XS
::Supportable
::ISA
, 'JSON';
456 my $pkg = 'JSON::Backend::XS::Supportable';
459 my $proto = new JSON
::XS
; $$proto = 0;
464 for my $method (@methods) {
465 my $flag = uc($method);
466 my $type |= (UNSUPPORTED_ENCODE_FLAG
->{$flag} || 0);
467 $type |= (UNSUPPORTED_DECODE_FLAG
->{$flag} || 0);
471 $pkg->_make_unsupported_method($method => $type);
474 push @
{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
475 push @
{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
477 $JSON::DEBUG
and Carp
::carp
("set -support_by_pp mode.");
486 # Helper classes for XS
489 package JSON
::Backend
::XS
::Supportable
;
491 $Carp::Internal
{'JSON::Backend::XS::Supportable'} = 1;
493 sub _make_unsupported_method
{
494 my ($pkg, $method, $type) = @_;
499 *{"$pkg\::$method"} = sub {
501 if (defined $_[1] ?
$_[1] : 1) {
510 *{"$pkg\::get_$method"} = sub {
511 ${$_[0]} & $type ?
1 : '';
518 JSON
::_load_pp
( $_INSTALL_ONLY );
521 my $pp = new JSON
::PP
;
522 my $prop = $_[0]->property;
524 for my $name (keys %$prop) {
525 $pp->$name( $prop->{$name} ?
$prop->{$name} : 0 );
528 my $unsupported = $type eq 'encode' ? JSON
::Backend
::XS
::UNSUPPORTED_ENCODE_FLAG
529 : JSON
::Backend
::XS
::UNSUPPORTED_DECODE_FLAG
;
530 my $flags = ${$_[0]} || 0;
532 for my $name (keys %$unsupported) {
533 next if ($name eq 'EXPANDED'); # for developer's
534 my $enable = ($flags & $unsupported->{$name}) ?
1 : 0;
535 my $method = lc $name;
536 $pp->$method($enable);
539 $pp->indent_length( $_[0]->get_indent_length );
544 sub _encode
{ # using with PP encod
546 _set_for_pp
('encode' => @_)->encode($_[1]);
549 $_[0]->_original_encode( $_[1] );
554 sub _decode
{ # if unsupported-flag is set, use PP
556 _set_for_pp
('decode' => @_)->decode($_[1]);
559 $_[0]->_original_decode( $_[1] );
564 sub decode_prefix
{ # if unsupported-flag is set, use PP
565 _set_for_pp
('decode' => @_)->decode_prefix($_[1]);
571 _set_for_pp
('decode' => @_)->incr_parse($_[1]);
574 $_[0]->_original_incr_parse( $_[1] );
579 sub get_indent_length
{
587 if (!defined $length or $length > 15 or $length < 0) {
588 Carp
::carp
"The acceptable range of indent_length() is 0 to 15.";
593 ${$_[0]} &= ~ JSON
::Backend
::XS
::INDENT_LENGTH_FLAG
;
595 *JSON
::XS
::encode
= \
&JSON
::Backend
::XS
::Supportable
::_encode
;
607 JSON - JSON (JavaScript Object Notation) encoder/decoder
611 use JSON; # imports encode_json, decode_json, to_json and from_json.
613 # simple and fast interfaces (expect/generate UTF-8)
615 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
616 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
620 $json = JSON->new->allow_nonref;
622 $json_text = $json->encode( $perl_scalar );
623 $perl_scalar = $json->decode( $json_text );
625 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
627 # If you want to use PP only support features, call with '-support_by_pp'
628 # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
630 use JSON -support_by_pp;
632 # option-acceptable interfaces (expect/generate UNICODE by default)
634 $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
635 $perl_scalar = from_json( $json_text, { utf8 => 1 } );
637 # Between (en|de)code_json and (to|from)_json, if you want to write
638 # a code which communicates to an outer world (encoded in UTF-8),
639 # recommend to use (en|de)code_json.
645 This version is compatible with JSON::XS B<2.27> and later.
650 JSON::PP was inculded in C<JSON> distribution.
651 It comes to be a perl core module in Perl 5.14.
652 And L<JSON::PP> will be split away it.
654 C<JSON> distribution will inculde yet another JSON::PP modules.
655 They are JSNO::backportPP and so on. JSON.pm should work as it did at all.
659 ************************** CAUTION ********************************
660 * This is 'JSON module version 2' and there are many differences *
662 * Please check your applications useing old version. *
663 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
664 *******************************************************************
666 JSON (JavaScript Object Notation) is a simple data format.
667 See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
669 This module converts Perl data structures to JSON and vice versa using either
670 L<JSON::XS> or L<JSON::PP>.
672 JSON::XS is the fastest and most proper JSON module on CPAN which must be
673 compiled and installed in your environment.
674 JSON::PP is a pure-Perl module which is bundled in this distribution and
675 has a strong compatibility to JSON::XS.
677 This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
678 So its features completely depend on JSON::XS or JSON::PP.
680 See to L<BACKEND MODULE DECISION>.
682 To distinguish the module name 'JSON' and the format type JSON,
683 the former is quoted by CE<lt>E<gt> (its results vary with your using media),
684 and the latter is left just as it is.
686 Module name : C<JSON>
694 =item * correct unicode handling
696 This module (i.e. backend modules) knows how to handle Unicode, documents
697 how and when it does so, and even documents what "correct" means.
699 Even though there are limitations, this feature is available since Perl version 5.6.
701 JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
702 C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005.
704 With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
705 JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
706 See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
708 See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
709 and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
712 =item * round-trip integrity
714 When you serialise a perl data structure using only data types supported
715 by JSON and Perl, the deserialised data structure is identical on the Perl
716 level. (e.g. the string "2.0" doesn't suddenly become "2" just because
717 it looks like a number). There I<are> minor exceptions to this, read the
718 L</MAPPING> section below to learn about those.
721 =item * strict checking of JSON correctness
723 There is no guessing, no generating of illegal JSON texts by default,
724 and only JSON is accepted as input by default (the latter is a security
727 See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
731 This module returns a JSON::XS object itself if available.
732 Compared to other JSON modules and other serialisers such as Storable,
733 JSON::XS usually compares favourably in terms of speed, too.
735 If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
736 it is very slow as pure-Perl.
738 =item * simple to use
740 This module has both a simple functional interface as well as an
741 object oriented interface interface.
743 =item * reasonably versatile output formats
745 You can choose between the most compact guaranteed-single-line format possible
746 (nice for simple line-based protocols), a pure-ASCII format (for when your transport
747 is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
748 format (for when you want to read that stuff). Or you can combine those features
749 in whatever way you like.
753 =head1 FUNCTIONAL INTERFACE
755 Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
756 C<to_json> and C<from_json> are additional functions.
760 $json_text = encode_json $perl_scalar
762 Converts the given Perl data structure to a UTF-8 encoded, binary string.
764 This function call is functionally identical to:
766 $json_text = JSON->new->utf8->encode($perl_scalar)
770 $perl_scalar = decode_json $json_text
772 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
773 to parse that as an UTF-8 encoded JSON text, returning the resulting
776 This function call is functionally identical to:
778 $perl_scalar = JSON->new->utf8->decode($json_text)
783 $json_text = to_json($perl_scalar)
785 Converts the given Perl data structure to a json string.
787 This function call is functionally identical to:
789 $json_text = JSON->new->encode($perl_scalar)
791 Takes a hash reference as the second.
793 $json_text = to_json($perl_scalar, $flag_hashref)
797 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
801 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
803 If you want to write a modern perl code which communicates to outer world,
804 you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
808 $perl_scalar = from_json($json_text)
810 The opposite of C<to_json>: expects a json string and tries
811 to parse it, returning the resulting reference.
813 This function call is functionally identical to:
815 $perl_scalar = JSON->decode($json_text)
817 Takes a hash reference as the second.
819 $perl_scalar = from_json($json_text, $flag_hashref)
823 $perl_scalar = from_json($json_text, {utf8 => 1})
827 $perl_scalar = JSON->new->utf8(1)->decode($json_text)
829 If you want to write a modern perl code which communicates to outer world,
830 you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
834 $is_boolean = JSON::is_bool($scalar)
836 Returns true if the passed scalar represents either JSON::true or
837 JSON::false, two constants that act like C<1> and C<0> respectively
838 and are also used to represent JSON C<true> and C<false> in Perl strings.
842 Returns JSON true value which is blessed object.
843 It C<isa> JSON::Boolean object.
847 Returns JSON false value which is blessed object.
848 It C<isa> JSON::Boolean object.
854 See L<MAPPING>, below, for more information on how JSON values are mapped to
857 =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
859 This section supposes that your perl vresion is 5.8 or later.
861 If you know a JSON text from an outer world - a network, a file content, and so on,
862 is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
863 with C<utf8> enable. And the decoded result will contain UNICODE characters.
866 my $json = JSON->new->utf8;
867 my $json_text = CGI->new->param( 'json_data' );
868 my $perl_scalar = $json->decode( $json_text );
872 open( my $fh, '<', 'json.data' );
874 $perl_scalar = decode_json( $json_text );
876 If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
880 open( my $fh, '<', 'json.data' );
881 my $encoding = 'cp932';
882 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
884 # or you can write the below code.
886 # open( my $fh, "<:encoding($encoding)", 'json.data' );
887 # $unicode_json_text = <$fh>;
889 In this case, C<$unicode_json_text> is of course UNICODE string.
890 So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
891 Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
893 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
895 $perl_scalar = from_json( $unicode_json_text );
897 Or C<encode 'utf8'> and C<decode_json>:
899 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
900 # this way is not efficient.
902 And now, you want to convert your C<$perl_scalar> into JSON data and
903 send it to an outer world - a network or a file content, and so on.
905 Your data usually contains UNICODE strings and you want the converted data to be encoded
906 in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
908 print encode_json( $perl_scalar ); # to a network? file? or display?
910 print $json->utf8->encode( $perl_scalar );
912 If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
913 for some reason, then its characters are regarded as B<latin1> for perl
914 (because it does not concern with your $encoding).
915 You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
916 Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
917 Note that the resulted text is a UNICODE string but no problem to print it.
919 # $perl_scalar contains $encoding encoded string values
920 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
922 $unicode_json_text = to_json( $perl_scalar );
923 # $unicode_json_text consists of characters less than 0x100
924 print $unicode_json_text;
926 Or C<decode $encoding> all string values and C<encode_json>:
928 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
929 # ... do it to each string values, then encode_json
930 $json_text = encode_json( $perl_scalar );
932 This method is a proper way but probably not efficient.
934 See to L<Encode>, L<perluniintro>.
937 =head1 COMMON OBJECT-ORIENTED INTERFACE
943 Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
944 that can be used to de/encode JSON strings.
946 All boolean flags described below are by default I<disabled>.
948 The mutators for flags all return the JSON object again and thus calls can
951 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
956 $json = $json->ascii([$enable])
958 $enabled = $json->get_ascii
960 If $enable is true (or missing), then the encode method will not generate characters outside
961 the code range 0..127. Any Unicode characters outside that range will be escaped using either
962 a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
964 If $enable is false, then the encode method will not escape Unicode characters unless
965 required by the JSON syntax or other flags. This results in a faster and more compact format.
967 This feature depends on the used Perl version and environment.
969 See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
971 JSON->new->ascii(1)->encode([chr 0x10401])
976 $json = $json->latin1([$enable])
978 $enabled = $json->get_latin1
980 If $enable is true (or missing), then the encode method will encode the resulting JSON
981 text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
983 If $enable is false, then the encode method will not escape Unicode characters
984 unless required by the JSON syntax or other flags.
986 JSON->new->latin1->encode (["\x{89}\x{abc}"]
987 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
991 $json = $json->utf8([$enable])
993 $enabled = $json->get_utf8
995 If $enable is true (or missing), then the encode method will encode the JSON result
996 into UTF-8, as required by many protocols, while the decode method expects to be handled
997 an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
998 characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
1000 In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
1001 encoding families, as described in RFC4627.
1003 If $enable is false, then the encode method will return the JSON string as a (non-encoded)
1004 Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
1005 (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
1008 Example, output UTF-16BE-encoded JSON:
1011 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
1013 Example, decode UTF-32LE-encoded JSON:
1016 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
1018 See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
1023 $json = $json->pretty([$enable])
1025 This enables (or disables) all of the C<indent>, C<space_before> and
1026 C<space_after> (and in the future possibly more) flags in one call to
1027 generate the most readable (or most compact) form possible.
1031 $json->indent->space_before->space_after
1033 The indent space length is three and JSON::XS cannot change the indent
1038 $json = $json->indent([$enable])
1040 $enabled = $json->get_indent
1042 If C<$enable> is true (or missing), then the C<encode> method will use a multiline
1043 format as output, putting every array member or object/hash key-value pair
1044 into its own line, identing them properly.
1046 If C<$enable> is false, no newlines or indenting will be produced, and the
1047 resulting JSON text is guarenteed not to contain any C<newlines>.
1049 This setting has no effect when decoding JSON texts.
1051 The indent space length is three.
1052 With JSON::PP, you can also access C<indent_length> to change indent space length.
1057 $json = $json->space_before([$enable])
1059 $enabled = $json->get_space_before
1061 If C<$enable> is true (or missing), then the C<encode> method will add an extra
1062 optional space before the C<:> separating keys from values in JSON objects.
1064 If C<$enable> is false, then the C<encode> method will not add any extra
1065 space at those places.
1067 This setting has no effect when decoding JSON texts.
1069 Example, space_before enabled, space_after and indent disabled:
1076 $json = $json->space_after([$enable])
1078 $enabled = $json->get_space_after
1080 If C<$enable> is true (or missing), then the C<encode> method will add an extra
1081 optional space after the C<:> separating keys from values in JSON objects
1082 and extra whitespace after the C<,> separating key-value pairs and array
1085 If C<$enable> is false, then the C<encode> method will not add any extra
1086 space at those places.
1088 This setting has no effect when decoding JSON texts.
1090 Example, space_before and indent disabled, space_after enabled:
1097 $json = $json->relaxed([$enable])
1099 $enabled = $json->get_relaxed
1101 If C<$enable> is true (or missing), then C<decode> will accept some
1102 extensions to normal JSON syntax (see below). C<encode> will not be
1103 affected in anyway. I<Be aware that this option makes you accept invalid
1104 JSON texts as if they were valid!>. I suggest only to use this option to
1105 parse application-specific files written by humans (configuration files,
1106 resource files etc.)
1108 If C<$enable> is false (the default), then C<decode> will only accept
1111 Currently accepted extensions are:
1115 =item * list items can have an end-comma
1117 JSON I<separates> array elements and key-value pairs with commas. This
1118 can be annoying if you write JSON texts manually and want to be able to
1119 quickly append elements, so this extension accepts comma at the end of
1120 such items not just between them:
1124 2, <- this comma not normally allowed
1128 "k2": "v2", <- this comma not normally allowed
1131 =item * shell-style '#'-comments
1133 Whenever JSON allows whitespace, shell-style comments are additionally
1134 allowed. They are terminated by the first carriage-return or line-feed
1135 character, after which more white-space and comments are allowed.
1138 1, # this comment not allowed in JSON
1139 # neither this one...
1147 $json = $json->canonical([$enable])
1149 $enabled = $json->get_canonical
1151 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
1152 by sorting their keys. This is adding a comparatively high overhead.
1154 If C<$enable> is false, then the C<encode> method will output key-value
1155 pairs in the order Perl stores them (which will likely change between runs
1156 of the same script).
1158 This option is useful if you want the same data structure to be encoded as
1159 the same JSON text (given the same overall settings). If it is disabled,
1160 the same hash might be encoded differently even if contains the same data,
1161 as key-value pairs have no inherent ordering in Perl.
1163 This setting has no effect when decoding JSON texts.
1167 $json = $json->allow_nonref([$enable])
1169 $enabled = $json->get_allow_nonref
1171 If C<$enable> is true (or missing), then the C<encode> method can convert a
1172 non-reference into its corresponding string, number or null JSON value,
1173 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
1174 values instead of croaking.
1176 If C<$enable> is false, then the C<encode> method will croak if it isn't
1177 passed an arrayref or hashref, as JSON texts must either be an object
1178 or array. Likewise, C<decode> will croak if given something that is not a
1179 JSON object or array.
1181 JSON->new->allow_nonref->encode ("Hello, World!")
1184 =head2 allow_unknown
1186 $json = $json->allow_unknown ([$enable])
1188 $enabled = $json->get_allow_unknown
1190 If $enable is true (or missing), then "encode" will *not* throw an
1191 exception when it encounters values it cannot represent in JSON (for
1192 example, filehandles) but instead will encode a JSON "null" value.
1193 Note that blessed objects are not included here and are handled
1194 separately by c<allow_nonref>.
1196 If $enable is false (the default), then "encode" will throw an
1197 exception when it encounters anything it cannot encode as JSON.
1199 This option does not affect "decode" in any way, and it is
1200 recommended to leave it off unless you know your communications
1203 =head2 allow_blessed
1205 $json = $json->allow_blessed([$enable])
1207 $enabled = $json->get_allow_blessed
1209 If C<$enable> is true (or missing), then the C<encode> method will not
1210 barf when it encounters a blessed reference. Instead, the value of the
1211 B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
1212 disabled or no C<TO_JSON> method found) or a representation of the
1213 object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
1214 encoded. Has no effect on C<decode>.
1216 If C<$enable> is false (the default), then C<encode> will throw an
1217 exception when it encounters a blessed object.
1220 =head2 convert_blessed
1222 $json = $json->convert_blessed([$enable])
1224 $enabled = $json->get_convert_blessed
1226 If C<$enable> is true (or missing), then C<encode>, upon encountering a
1227 blessed object, will check for the availability of the C<TO_JSON> method
1228 on the object's class. If found, it will be called in scalar context
1229 and the resulting scalar will be encoded instead of the object. If no
1230 C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
1233 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
1234 returns other blessed objects, those will be handled in the same
1235 way. C<TO_JSON> must take care of not causing an endless recursion cycle
1236 (== crash) in this case. The name of C<TO_JSON> was chosen because other
1237 methods called by the Perl core (== not by the user of the object) are
1238 usually in upper case letters and to avoid collisions with the C<to_json>
1241 This setting does not yet influence C<decode> in any way.
1243 If C<$enable> is false, then the C<allow_blessed> setting will decide what
1244 to do when a blessed object is found.
1248 =item convert_blessed_universally mode
1250 If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
1251 subroutine is defined as the below code:
1253 *UNIVERSAL::TO_JSON = sub {
1254 my $b_obj = B::svref_2object( $_[0] );
1255 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
1256 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
1261 This will cause that C<encode> method converts simple blessed objects into
1262 JSON objects as non-blessed object.
1264 JSON -convert_blessed_universally;
1265 $json->allow_blessed->convert_blessed->encode( $blessed_object )
1267 This feature is experimental and may be removed in the future.
1271 =head2 filter_json_object
1273 $json = $json->filter_json_object([$coderef])
1275 When C<$coderef> is specified, it will be called from C<decode> each
1276 time it decodes a JSON object. The only argument passed to the coderef
1277 is a reference to the newly-created hash. If the code references returns
1278 a single scalar (which need not be a reference), this value
1279 (i.e. a copy of that scalar to avoid aliasing) is inserted into the
1280 deserialised data structure. If it returns an empty list
1281 (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
1282 hash will be inserted. This setting can slow down decoding considerably.
1284 When C<$coderef> is omitted or undefined, any existing callback will
1285 be removed and C<decode> will not change the deserialised hash in any
1288 Example, convert all JSON objects into the integer 5:
1290 my $js = JSON->new->filter_json_object (sub { 5 });
1292 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
1293 # throw an exception because allow_nonref is not enabled
1294 # so a lone 5 is not allowed.
1295 $js->decode ('{"a":1, "b":2}');
1298 =head2 filter_json_single_key_object
1300 $json = $json->filter_json_single_key_object($key [=> $coderef])
1302 Works remotely similar to C<filter_json_object>, but is only called for
1303 JSON objects having a single key named C<$key>.
1305 This C<$coderef> is called before the one specified via
1306 C<filter_json_object>, if any. It gets passed the single value in the JSON
1307 object. If it returns a single value, it will be inserted into the data
1308 structure. If it returns nothing (not even C<undef> but the empty list),
1309 the callback from C<filter_json_object> will be called next, as if no
1310 single-key callback were specified.
1312 If C<$coderef> is omitted or undefined, the corresponding callback will be
1313 disabled. There can only ever be one callback for a given key.
1315 As this callback gets called less often then the C<filter_json_object>
1316 one, decoding speed will not usually suffer as much. Therefore, single-key
1317 objects make excellent targets to serialise Perl objects into, especially
1318 as single-key JSON objects are as close to the type-tagged value concept
1319 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
1320 support this in any way, so you need to make sure your data never looks
1321 like a serialised Perl hash.
1323 Typical names for the single object key are C<__class_whatever__>, or
1324 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
1325 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
1328 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
1329 into the corresponding C<< $WIDGET{<id>} >> object:
1331 # return whatever is in $WIDGET{5}:
1334 ->filter_json_single_key_object (__widget__ => sub {
1337 ->decode ('{"__widget__": 5')
1339 # this can be used with a TO_JSON method in some "widget" class
1340 # for serialisation to json:
1341 sub WidgetBase::TO_JSON {
1344 unless ($self->{id}) {
1345 $self->{id} = ..get..some..id..;
1346 $WIDGET{$self->{id}} = $self;
1349 { __widget__ => $self->{id} }
1355 $json = $json->shrink([$enable])
1357 $enabled = $json->get_shrink
1359 With JSON::XS, this flag resizes strings generated by either
1360 C<encode> or C<decode> to their minimum size possible. This can save
1361 memory when your JSON texts are either very very long or you have many
1362 short strings. It will also try to downgrade any strings to octet-form
1363 if possible: perl stores strings internally either in an encoding called
1364 UTF-X or in octet-form. The latter cannot store everything but uses less
1365 space in general (and some buggy Perl or C code might even rely on that
1366 internal representation being used).
1368 With JSON::PP, it is noop about resizing strings but tries
1369 C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
1371 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
1375 $json = $json->max_depth([$maximum_nesting_depth])
1377 $max_depth = $json->get_max_depth
1379 Sets the maximum nesting level (default C<512>) accepted while encoding
1380 or decoding. If a higher nesting level is detected in JSON text or a Perl
1381 data structure, then the encoder and decoder will stop and croak at that
1384 Nesting level is defined by number of hash- or arrayrefs that the encoder
1385 needs to traverse to reach a given point or the number of C<{> or C<[>
1386 characters without their matching closing parenthesis crossed to reach a
1387 given character in a string.
1389 If no argument is given, the highest possible setting will be used, which
1392 Note that nesting is implemented by recursion in C. The default value has
1393 been chosen to be as large as typical operating systems allow without
1394 crashing. (JSON::XS)
1396 With JSON::PP as the backend, when a large value (100 or more) was set and
1397 it de/encodes a deep nested object/text, it may raise a warning
1398 'Deep recursion on subroutin' at the perl runtime phase.
1400 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1404 $json = $json->max_size([$maximum_string_size])
1406 $max_size = $json->get_max_size
1408 Set the maximum length a JSON text may have (in bytes) where decoding is
1409 being attempted. The default is C<0>, meaning no limit. When C<decode>
1410 is called on a string that is longer then this many bytes, it will not
1411 attempt to decode the string but throw an exception. This setting has no
1412 effect on C<encode> (yet).
1414 If no argument is given, the limit check will be deactivated (same as when
1417 See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
1421 $json_text = $json->encode($perl_scalar)
1423 Converts the given Perl data structure (a simple scalar or a reference
1424 to a hash or array) to its JSON representation. Simple scalars will be
1425 converted into JSON string or number sequences, while references to arrays
1426 become JSON arrays and references to hashes become JSON objects. Undefined
1427 Perl values (e.g. C<undef>) become JSON C<null> values.
1428 References to the integers C<0> and C<1> are converted into C<true> and C<false>.
1432 $perl_scalar = $json->decode($json_text)
1434 The opposite of C<encode>: expects a JSON text and tries to parse it,
1435 returning the resulting simple scalar or reference. Croaks on error.
1437 JSON numbers and strings become simple Perl scalars. JSON arrays become
1438 Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
1439 C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
1440 C<null> becomes C<undef>.
1442 =head2 decode_prefix
1444 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
1446 This works like the C<decode> method, but instead of raising an exception
1447 when there is trailing garbage after the first JSON object, it will
1448 silently stop parsing there and return the number of characters consumed
1451 JSON->new->decode_prefix ("[1] the tail")
1454 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
1458 $boolean = $json->property($property_name)
1460 Returns a boolean value about above some properties.
1462 The available properties are C<ascii>, C<latin1>, C<utf8>,
1463 C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
1464 C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
1465 C<shrink>, C<max_depth> and C<max_size>.
1467 $boolean = $json->property('utf8');
1470 $boolean = $json->property('utf8');
1473 Sets the property with a given boolean value.
1475 $json = $json->property($property_name => $boolean);
1477 With no argumnt, it returns all the above properties as a hash reference.
1479 $flag_hashref = $json->property();
1481 =head1 INCREMENTAL PARSING
1483 Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
1485 In some cases, there is the need for incremental parsing of JSON texts.
1486 This module does allow you to parse a JSON stream incrementally.
1487 It does so by accumulating text until it has a full JSON object, which
1488 it then can decode. This process is similar to using C<decode_prefix>
1489 to see if a full JSON object is available, but is much more efficient
1490 (and can be implemented with a minimum of method calls).
1492 The backend module will only attempt to parse the JSON text once it is sure it
1493 has enough text to get a decisive result, using a very simple but
1494 truly incremental parser. This means that it sometimes won't stop as
1495 early as the full parser, for example, it doesn't detect parenthese
1496 mismatches. The only thing it guarantees is that it starts decoding as
1497 soon as a syntactically valid JSON text has been seen. This means you need
1498 to set resource limits (e.g. C<max_size>) to ensure the parser will stop
1499 parsing in the presence if syntax errors.
1501 The following methods implement this incremental parser.
1505 $json->incr_parse( [$string] ) # void context
1507 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
1509 @obj_or_empty = $json->incr_parse( [$string] ) # list context
1511 This is the central parsing function. It can both append new text and
1512 extract objects from the stream accumulated so far (both of these
1513 functions are optional).
1515 If C<$string> is given, then this string is appended to the already
1516 existing JSON fragment stored in the C<$json> object.
1518 After that, if the function is called in void context, it will simply
1519 return without doing anything further. This can be used to add more text
1520 in as many chunks as you want.
1522 If the method is called in scalar context, then it will try to extract
1523 exactly I<one> JSON object. If that is successful, it will return this
1524 object, otherwise it will return C<undef>. If there is a parse error,
1525 this method will croak just as C<decode> would do (one can then use
1526 C<incr_skip> to skip the errornous part). This is the most common way of
1529 And finally, in list context, it will try to extract as many objects
1530 from the stream as it can find and return them, or the empty list
1531 otherwise. For this to work, there must be no separators between the JSON
1532 objects or arrays, instead they must be concatenated back-to-back. If
1533 an error occurs, an exception will be raised as in the scalar context
1534 case. Note that in this case, any previously-parsed JSON texts will be
1537 Example: Parse some JSON arrays/objects in a given string and return them.
1539 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
1543 $lvalue_string = $json->incr_text
1545 This method returns the currently stored JSON fragment as an lvalue, that
1546 is, you can manipulate it. This I<only> works when a preceding call to
1547 C<incr_parse> in I<scalar context> successfully returned an object. Under
1548 all other circumstances you must not call this function (I mean it.
1549 although in simple tests it might actually work, it I<will> fail under
1550 real world conditions). As a special exception, you can also call this
1551 method before having parsed anything.
1553 This function is useful in two cases: a) finding the trailing text after a
1554 JSON object or b) parsing multiple JSON objects separated by non-JSON text
1557 $json->incr_text =~ s/\s*,\s*//;
1559 In Perl 5.005, C<lvalue> attribute is not available.
1560 You must write codes like the below:
1562 $string = $json->incr_text;
1563 $string =~ s/\s*,\s*//;
1564 $json->incr_text( $string );
1570 This will reset the state of the incremental parser and will remove the
1571 parsed text from the input buffer. This is useful after C<incr_parse>
1572 died, in which case the input buffer and incremental parser state is left
1573 unchanged, to skip the text parsed so far and to reset the parse state.
1579 This completely resets the incremental parser, that is, after this call,
1580 it will be as if the parser had never parsed anything.
1582 This is useful if you want ot repeatedly parse JSON objects and want to
1583 ignore any trailing data, which means you have to reset the parser after
1584 each successful decode.
1586 See to L<JSON::XS/INCREMENTAL PARSING> for examples.
1589 =head1 JSON::PP SUPPORT METHODS
1591 The below methods are JSON::PP own methods, so when C<JSON> works
1592 with JSON::PP (i.e. the created object is a JSON::PP object), available.
1593 See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
1595 If you use C<JSON> with additonal C<-support_by_pp>, some methods
1596 are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
1598 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
1600 use JSON -support_by_pp;
1602 my $json = new JSON;
1603 $json->allow_nonref->escape_slash->encode("/");
1605 # functional interfaces too.
1606 print to_json(["/"], {escape_slash => 1});
1607 print from_json('["foo"]', {utf8 => 1});
1609 If you do not want to all functions but C<-support_by_pp>,
1612 use JSON -support_by_pp, -no_export;
1613 # functional interfaces are not exported.
1615 =head2 allow_singlequote
1617 $json = $json->allow_singlequote([$enable])
1619 If C<$enable> is true (or missing), then C<decode> will accept
1620 any JSON strings quoted by single quotations that are invalid JSON
1623 $json->allow_singlequote->decode({"foo":'bar'});
1624 $json->allow_singlequote->decode({'foo':"bar"});
1625 $json->allow_singlequote->decode({'foo':'bar'});
1627 As same as the C<relaxed> option, this option may be used to parse
1628 application-specific files written by humans.
1630 =head2 allow_barekey
1632 $json = $json->allow_barekey([$enable])
1634 If C<$enable> is true (or missing), then C<decode> will accept
1635 bare keys of JSON object that are invalid JSON format.
1637 As same as the C<relaxed> option, this option may be used to parse
1638 application-specific files written by humans.
1640 $json->allow_barekey->decode('{foo:"bar"}');
1644 $json = $json->allow_bignum([$enable])
1646 If C<$enable> is true (or missing), then C<decode> will convert
1647 the big integer Perl cannot handle as integer into a L<Math::BigInt>
1648 object and convert a floating number (any) into a L<Math::BigFloat>.
1650 On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1651 objects into JSON numbers with C<allow_blessed> enable.
1653 $json->allow_nonref->allow_blessed->allow_bignum;
1654 $bigfloat = $json->decode('2.000000000000000000000000001');
1655 print $json->encode($bigfloat);
1656 # => 2.000000000000000000000000001
1658 See to L<MAPPING> aboout the conversion of JSON number.
1662 $json = $json->loose([$enable])
1664 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
1665 and the module doesn't allow to C<decode> to these (except for \x2f).
1666 If C<$enable> is true (or missing), then C<decode> will accept these
1669 $json->loose->decode(qq|["abc
1672 See to L<JSON::PP/JSON::PP OWN METHODS>.
1676 $json = $json->escape_slash([$enable])
1678 According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
1679 JSON backend modules encode strings without escaping slash.
1681 If C<$enable> is true (or missing), then C<encode> will escape slashes.
1683 =head2 indent_length
1685 $json = $json->indent_length($length)
1687 With JSON::XS, The indent space length is 3 and cannot be changed.
1688 With JSON::PP, it sets the indent space length with the given $length.
1689 The default is 3. The acceptable range is 0 to 15.
1693 $json = $json->sort_by($function_name)
1694 $json = $json->sort_by($subroutine_ref)
1696 If $function_name or $subroutine_ref are set, its sort routine are used.
1698 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
1699 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1701 $js = $pc->sort_by('own_sort')->encode($obj);
1702 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1704 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
1706 As the sorting routine runs in the JSON::PP scope, the given
1707 subroutine name and the special variables C<$a>, C<$b> will begin
1710 If $integer is set, then the effect is same as C<canonical> on.
1712 See to L<JSON::PP/JSON::PP OWN METHODS>.
1716 This section is copied from JSON::XS and modified to C<JSON>.
1717 JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
1719 See to L<JSON::XS/MAPPING>.
1727 A JSON object becomes a reference to a hash in Perl. No ordering of object
1728 keys is preserved (JSON does not preserver object key ordering itself).
1732 A JSON array becomes a reference to an array in Perl.
1736 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1737 are represented by the same codepoints in the Perl string, so no manual
1738 decoding is necessary.
1742 A JSON number becomes either an integer, numeric (floating point) or
1743 string scalar in perl, depending on its range and any fractional parts. On
1744 the Perl level, there is no difference between those as Perl handles all
1745 the conversion details, but an integer may take slightly less memory and
1746 might represent more values exactly than floating point numbers.
1748 If the number consists of digits only, C<JSON> will try to represent
1749 it as an integer value. If that fails, it will try to represent it as
1750 a numeric (floating point) value if that is possible without loss of
1751 precision. Otherwise it will preserve the number as a string value (in
1752 which case you lose roundtripping ability, as the JSON number will be
1753 re-encoded toa JSON string).
1755 Numbers containing a fractional or exponential part will always be
1756 represented as numeric (floating point) values, possibly at a loss of
1757 precision (in which case you might lose perfect roundtripping ability, but
1758 the JSON number will still be re-encoded as a JSON number).
1760 Note that precision is not accuracy - binary floating point values cannot
1761 represent most decimal fractions exactly, and when converting from and to
1762 floating point, C<JSON> only guarantees precision up to but not including
1763 the leats significant bit.
1765 If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
1766 and the numeric can be optionally converted into L<Math::BigInt> and
1767 L<Math::BigFloat> objects.
1771 These JSON atoms become C<JSON::true> and C<JSON::false>,
1772 respectively. They are overloaded to act almost exactly like the numbers
1773 C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
1774 the C<JSON::is_bool> function.
1776 If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
1777 they represent as C<true> and C<false> respectively.
1779 print JSON::true . "\n";
1781 print JSON::true + 1;
1784 ok(JSON::true eq 'true');
1785 ok(JSON::true eq '1');
1786 ok(JSON::true == 1);
1788 C<JSON> will install these missing overloading features to the backend modules.
1793 A JSON null atom becomes C<undef> in Perl.
1795 C<JSON::null> returns C<unddef>.
1802 The mapping from Perl to JSON is slightly more difficult, as Perl is a
1803 truly typeless language, so we can only guess which JSON type is meant by
1808 =item hash references
1810 Perl hash references become JSON objects. As there is no inherent ordering
1811 in hash keys (or JSON objects), they will usually be encoded in a
1812 pseudo-random order that can change between runs of the same program but
1813 stays generally the same within a single run of a program. C<JSON>
1814 optionally sort the hash keys (determined by the I<canonical> flag), so
1815 the same datastructure will serialise to the same JSON text (given same
1816 settings and version of JSON::XS), but this incurs a runtime overhead
1817 and is only rarely useful, e.g. when you want to compare some JSON text
1818 against another for equality.
1820 In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
1823 =item array references
1825 Perl array references become JSON arrays.
1827 =item other references
1829 Other unblessed references are generally not allowed and will cause an
1830 exception to be thrown, except for references to the integers C<0> and
1831 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1832 also use C<JSON::false> and C<JSON::true> to improve readability.
1834 to_json [\0,JSON::true] # yields [false,true]
1836 =item JSON::true, JSON::false, JSON::null
1838 These special values become JSON true and JSON false values,
1839 respectively. You can also use C<\1> and C<\0> directly if you want.
1841 JSON::null returns C<undef>.
1843 =item blessed objects
1845 Blessed objects are not directly representable in JSON. See the
1846 C<allow_blessed> and C<convert_blessed> methods on various options on
1847 how to deal with this: basically, you can choose between throwing an
1848 exception, encoding the reference as if it weren't blessed, or provide
1849 your own serialiser method.
1851 With C<convert_blessed_universally> mode, C<encode> converts blessed
1852 hash references or blessed array references (contains other blessed references)
1853 into JSON members and arrays.
1855 use JSON -convert_blessed_universally;
1856 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
1858 See to L<convert_blessed>.
1860 =item simple scalars
1862 Simple Perl scalars (any scalar that is not a reference) are the most
1863 difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
1864 JSON C<null> values, scalars that have last been used in a string context
1865 before encoding as JSON strings, and anything else as number value:
1868 encode_json [2] # yields [2]
1869 encode_json [-3.0e17] # yields [-3e+17]
1870 my $value = 5; encode_json [$value] # yields [5]
1872 # used as string, so dump as string
1874 encode_json [$value] # yields ["5"]
1876 # undef becomes null
1877 encode_json [undef] # yields [null]
1879 You can force the type to be a string by stringifying it:
1881 my $x = 3.1; # some variable containing a number
1883 $x .= ""; # another, more awkward way to stringify
1884 print $x; # perl does it for you, too, quite often
1886 You can force the type to be a number by numifying it:
1888 my $x = "3"; # some variable containing a string
1889 $x += 0; # numify it, ensuring it will be dumped as a number
1890 $x *= 1; # same thing, the choise is yours.
1892 You can not currently force the type in other, less obscure, ways.
1894 Note that numerical precision has the same meaning as under Perl (so
1895 binary to decimal conversion follows the same rules as in Perl, which
1896 can differ to other languages). Also, your perl interpreter might expose
1897 extensions to the floating point numbers of your platform, such as
1898 infinities or NaN's - these cannot be represented in JSON, and it is an
1899 error to pass those in.
1903 If the backend is JSON::PP and C<allow_bignum> is enable,
1904 C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1905 objects into JSON numbers.
1910 =head1 JSON and ECMAscript
1912 See to L<JSON::XS/JSON and ECMAscript>.
1914 =head1 JSON and YAML
1916 JSON is not a subset of YAML.
1917 See to L<JSON::XS/JSON and YAML>.
1920 =head1 BACKEND MODULE DECISION
1922 When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
1923 C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
1925 The C<JSON> constructor method returns an object inherited from the backend module,
1926 and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash
1929 So, your program should not depend on the backend module, especially
1930 returned objects should not be modified.
1932 my $json = JSON->new; # XS or PP?
1933 $json->{stash} = 'this is xs object'; # this code may raise an error!
1935 To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
1937 JSON->backend; # 'JSON::XS' or 'JSON::PP'
1939 JSON->backend->is_pp: # 0 or 1
1941 JSON->backend->is_xs: # 1 or 0
1943 $json->is_xs; # 1 or 0
1945 $json->is_pp; # 0 or 1
1948 If you set an enviornment variable C<PERL_JSON_BACKEND>, The calling action will be changed.
1952 =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
1956 =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
1958 (The default) Use compiled JSON::XS if it is properly compiled & installed,
1959 otherwise use JSON::PP.
1961 =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
1963 Always use compiled JSON::XS, die if it isn't properly compiled & installed.
1965 =item PERL_JSON_BACKEND = 'JSON::backportPP'
1967 Always use JSON::backportPP.
1968 JSON::backportPP is JSON::PP back port module.
1969 C<JSON> includs JSON::backportPP instead of JSON::PP.
1973 These ideas come from L<DBI::PurePerl> mechanism.
1977 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
1978 use JSON; # always uses JSON::PP
1980 In future, it may be able to specify another module.
1982 =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
1984 Many methods are available with either JSON::XS or JSON::PP and
1985 when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported)
1986 method is called, it will C<warn> and be noop.
1988 But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
1989 it makes a part of those unupported methods available.
1990 This feature is achieved by using JSON::PP in C<de/encode>.
1992 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
1993 use JSON -support_by_pp;
1994 my $json = new JSON;
1995 $json->allow_nonref->escape_slash->encode("/");
1997 At this time, the returned object is a C<JSON::Backend::XS::Supportable>
1998 object (re-blessed XS object), and by checking JSON::XS unsupported flags
1999 in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
2000 C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
2002 When any unsupported methods are not enable, C<XS de/encode> will be
2003 used as is. The switch is achieved by changing the symbolic tables.
2005 C<-support_by_pp> is effective only when the backend module is JSON::XS
2006 and it makes the de/encoding speed down a bit.
2008 See to L<JSON::PP SUPPORT METHODS>.
2010 =head1 INCOMPATIBLE CHANGES TO OLD VERSION
2012 There are big incompatibility between new version (2.00) and old (1.xx).
2013 If you use old C<JSON> 1.xx in your code, please check it.
2015 See to L<Transition ways from 1.xx to 2.xx.>
2019 =item jsonToObj and objToJson are obsoleted.
2021 Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
2022 (but not yet deleted from the source).
2023 If you use these functions in your code, please replace them
2024 with C<from_json> and C<to_json>.
2027 =item Global variables are no longer available.
2029 C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
2030 - are not available any longer.
2031 Instead, various features can be used through object methods.
2034 =item Package JSON::Converter and JSON::Parser are deleted.
2036 Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
2038 =item Package JSON::NotString is deleted.
2040 There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
2041 and numbers. It was deleted and replaced by C<JSON::Boolean>.
2043 C<JSON::Boolean> represents C<true> and C<false>.
2045 C<JSON::Boolean> does not represent C<null>.
2047 C<JSON::null> returns C<undef>.
2049 C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
2050 to L<JSON::Boolean>.
2052 =item function JSON::Number is obsoleted.
2054 C<JSON::Number> is now needless because JSON::XS and JSON::PP have
2055 round-trip integrity.
2057 =item JSONRPC modules are deleted.
2059 Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
2060 and C<Apache::JSONRPC > are deleted in this distribution.
2061 Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
2065 =head2 Transition ways from 1.xx to 2.xx.
2067 You should set C<suport_by_pp> mode firstly, because
2068 it is always successful for the below codes even with JSON::XS.
2070 use JSON -support_by_pp;
2074 =item Exported jsonToObj (simple)
2076 from_json($json_text);
2078 =item Exported objToJson (simple)
2080 to_json($perl_scalar);
2082 =item Exported jsonToObj (advanced)
2084 $flags = {allow_barekey => 1, allow_singlequote => 1};
2085 from_json($json_text, $flags);
2090 $JSON::QuotApos = 1;
2091 jsonToObj($json_text);
2093 =item Exported objToJson (advanced)
2095 $flags = {allow_blessed => 1, allow_barekey => 1};
2096 to_json($perl_scalar, $flags);
2101 objToJson($perl_scalar);
2103 =item jsonToObj as object method
2105 $json->decode($json_text);
2107 =item objToJson as object method
2109 $json->encode($perl_scalar);
2111 =item new method with parameters
2113 The C<new> method in 2.x takes any parameters no longer.
2114 You can set parameters instead;
2116 $json = JSON->new->pretty;
2118 =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
2120 If C<indent> is enable, that means C<$JSON::Pretty> flag set. And
2121 C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
2124 $json->indent->space_before->space_after;
2130 To change indent length, use C<indent_length>.
2132 (Only with JSON::PP, if C<-support_by_pp> is not used.)
2134 $json->pretty->indent_length(2)->encode($perl_scalar);
2136 =item $JSON::BareKey
2138 (Only with JSON::PP, if C<-support_by_pp> is not used.)
2140 $json->allow_barekey->decode($json_text)
2142 =item $JSON::ConvBlessed
2144 use C<-convert_blessed_universally>. See to L<convert_blessed>.
2146 =item $JSON::QuotApos
2148 (Only with JSON::PP, if C<-support_by_pp> is not used.)
2150 $json->allow_singlequote->decode($json_text)
2152 =item $JSON::SingleQuote
2154 Disable. C<JSON> does not make such a invalid JSON string any longer.
2156 =item $JSON::KeySort
2158 $json->canonical->encode($perl_scalar)
2160 This is the ascii sort.
2162 If you want to use with your own sort routine, check the C<sort_by> method.
2164 (Only with JSON::PP, even if C<-support_by_pp> is used currently.)
2166 $json->sort_by($sort_routine_ref)->encode($perl_scalar)
2168 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
2170 Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
2172 =item $JSON::SkipInvalid
2174 $json->allow_unknown
2176 =item $JSON::AUTOCONVERT
2178 Needless. C<JSON> backend modules have the round-trip integrity.
2182 Needless because C<JSON> (JSON::XS/JSON::PP) sets
2183 the UTF8 flag on properly.
2185 # With UTF8-flagged strings
2187 $json->allow_nonref;
2188 $str = chr(1000); # UTF8-flagged
2190 $json_text = $json->utf8(0)->encode($str);
2191 utf8::is_utf8($json_text);
2193 $json_text = $json->utf8(1)->encode($str);
2194 utf8::is_utf8($json_text);
2197 $str = '"' . chr(1000) . '"'; # UTF8-flagged
2199 $perl_scalar = $json->utf8(0)->decode($str);
2200 utf8::is_utf8($perl_scalar);
2202 $perl_scalar = $json->utf8(1)->decode($str);
2203 # died because of 'Wide character in subroutine'
2205 See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
2207 =item $JSON::UnMapping
2209 Disable. See to L<MAPPING>.
2211 =item $JSON::SelfConvert
2213 This option was deleted.
2214 Instead of it, if a givien blessed object has the C<TO_JSON> method,
2215 C<TO_JSON> will be executed with C<convert_blessed>.
2217 $json->convert_blessed->encode($bleesed_hashref_or_arrayref)
2218 # if need, call allow_blessed
2220 Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
2228 =item example programs
2234 No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
2239 Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
2244 Most of the document is copied and modified from JSON::XS doc.
2246 L<JSON::XS>, L<JSON::PP>
2248 C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
2252 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
2254 JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
2256 The relese of this new version owes to the courtesy of Marc Lehmann.
2259 =head1 COPYRIGHT AND LICENSE
2261 Copyright 2005-2011 by Makamaka Hannyaharamitu
2263 This library is free software; you can redistribute it and/or modify
2264 it under the same terms as Perl itself.