7 @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
10 $JSON::VERSION = '2.16';
11 $JSON::DEBUG = 0 unless (defined $JSON::DEBUG);
14 my $Module_XS = 'JSON::XS';
15 my $Module_PP = 'JSON::PP';
16 my $XS_Version = '2.26';
19 # XS and PP common methods
21 my @PublicMethods = qw/
22 ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref
23 allow_blessed convert_blessed filter_json_object filter_json_single_key_object
24 shrink max_depth max_size encode decode decode_prefix allow_unknown
28 ascii latin1 utf8 indent space_before space_after relaxed canonical allow_nonref
29 allow_blessed convert_blessed shrink max_depth max_size allow_unknown
32 my @XSOnlyMethods = qw//; # Currently nothing
34 my @PPOnlyMethods = qw/
36 allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed
37 /; # JSON::PP specific
40 # used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently)
41 my $_INSTALL_DONT_DIE = 1; # When _load_xs fails to load XS, don't die.
42 my $_INSTALL_ONLY = 2; # Don't call _set_methods()
43 my $_ALLOW_UNSUPPORTED = 0;
44 my $_UNIV_CONV_BLESSED = 0;
47 # Check the environment variable to decide worker module.
49 unless ($JSON::Backend) {
50 $JSON::DEBUG and Carp::carp("Check used worker module...");
52 my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1;
54 if ($backend eq '1' or $backend =~ /JSON::XS\s*,\s*JSON::PP/) {
55 _load_xs($_INSTALL_DONT_DIE) or _load_pp();
57 elsif ($backend eq '0' or $backend eq 'JSON::PP') {
60 elsif ($backend eq '2' or $backend eq 'JSON::XS') {
64 Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid.";
75 if ($tag eq '-support_by_pp') {
76 if (!$_ALLOW_UNSUPPORTED++) {
78 ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend eq $Module_XS);
82 elsif ($tag eq '-no_export') {
85 elsif ( $tag eq '-convert_blessed_universally' ) {
88 *UNIVERSAL::TO_JSON = sub {
89 my $b_obj = B::svref_2object( $_[0] );
90 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
91 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
95 | if ( !$_UNIV_CONV_BLESSED++ );
98 push @what_to_export, $tag;
101 return if ($no_export);
103 __PACKAGE__->export_to_level(1, $pkg, @what_to_export);
110 my $alternative = 'from_json';
111 if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
112 shift @_; $alternative = 'decode';
114 Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead.";
115 return JSON::from_json(@_);
119 my $alternative = 'to_json';
120 if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
121 shift @_; $alternative = 'encode';
123 Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead.";
133 if (@_ == 2 and ref $_[1] eq 'HASH') {
135 for my $method (keys %$opt) {
136 $json->$method( $opt->{$method} );
140 $json->encode($_[0]);
147 if (@_ == 2 and ref $_[1] eq 'HASH') {
149 for my $method (keys %$opt) {
150 $json->$method( $opt->{$method} );
154 return $json->decode( $_[0] );
158 sub true { $JSON::true }
160 sub false { $JSON::false }
165 sub require_xs_version { $XS_Version; }
176 return $_[0]->module eq $Module_XS;
181 return $_[0]->module eq $Module_PP;
185 sub pureperl_only_methods { @PPOnlyMethods; }
189 my ($self, $name, $value) = @_;
193 for $name (@Properties) {
194 my $method = 'get_' . $name;
195 if ($name eq 'max_size') {
196 my $value = $self->$method();
197 $props{$name} = $value == 1 ? 0 : $value;
200 $props{$name} = $self->$method();
205 Carp::croak('property() can take only the option within 2 arguments.');
208 if ( my $method = $self->can('get_' . $name) ) {
209 if ($name eq 'max_size') {
210 my $value = $self->$method();
211 return $value == 1 ? 0 : $value;
217 $self->$name($value);
229 $JSON::DEBUG and Carp::carp "Load $Module_XS.";
231 # if called after install module, overload is disable.... why?
232 JSON::Boolean::_overrride_overload($Module_XS);
233 JSON::Boolean::_overrride_overload($Module_PP);
236 use $Module_XS $XS_Version ();
240 if (defined $opt and $opt & $_INSTALL_DONT_DIE) {
241 $JSON::DEBUG and Carp::carp "Can't load $Module_XS...($@)";
247 unless (defined $opt and $opt & $_INSTALL_ONLY) {
248 _set_module( $JSON::Backend = $Module_XS );
249 my $data = join("", <DATA>); # this code is from Jcode 2.xx.
252 JSON::Backend::XS->init;
262 $JSON::DEBUG and Carp::carp "Load $Module_PP.";
264 # if called after install module, overload is disable.... why?
265 JSON::Boolean::_overrride_overload($Module_XS);
266 JSON::Boolean::_overrride_overload($Module_PP);
268 eval qq| require $Module_PP |;
273 unless (defined $opt and $opt & $_INSTALL_ONLY) {
274 _set_module( $JSON::Backend = $Module_PP );
275 JSON::Backend::PP->init;
286 $JSON::true = ${"$module\::true"};
287 $JSON::false = ${"$module\::false"};
289 push @JSON::ISA, $module;
290 push @{"$module\::Boolean::ISA"}, qw(JSON::Boolean);
292 *{"JSON::is_bool"} = \&{"$module\::is_bool"};
294 for my $method ($module eq $Module_XS ? @PPOnlyMethods : @XSOnlyMethods) {
295 *{"JSON::$method"} = sub {
296 Carp::carp("$method is not supported in $module.");
310 package JSON::Boolean;
314 sub _overrride_overload {
315 return if ($Installed{ $_[0] }++);
317 my $boolean = $_[0] . '::Boolean';
322 '""' => sub { ${$_[0]} == 1 ? 'true' : 'false' },
324 my ($obj, $op) = ref ($_[0]) ? ($_[0], $_[1]) : ($_[1], $_[0]);
325 if ($op eq 'true' or $op eq 'false') {
326 return "$obj" eq 'true' ? 'true' eq $op : 'false' eq $op;
329 return $obj ? 1 == $op : 0 == $op;
335 if ($@) { Carp::croak $@; }
342 # Helper classes for Backend Module (PP)
345 package JSON::Backend::PP;
350 *{"JSON::decode_json"} = \&{"JSON::PP::decode_json"};
351 *{"JSON::encode_json"} = \&{"JSON::PP::encode_json"};
352 *{"JSON::PP::is_xs"} = sub { 0 };
353 *{"JSON::PP::is_pp"} = sub { 1 };
358 # To save memory, the below lines are read only when XS backend is used.
368 # Helper classes for Backend Module (XS)
371 package JSON::Backend::XS;
373 use constant INDENT_LENGTH_FLAG => 15 << 12;
375 use constant UNSUPPORTED_ENCODE_FLAG => {
376 ESCAPE_SLASH => 0x00000010,
377 ALLOW_BIGNUM => 0x00000020,
378 AS_NONBLESSED => 0x00000040,
379 EXPANDED => 0x10000000, # for developer's
382 use constant UNSUPPORTED_DECODE_FLAG => {
384 ALLOW_BIGNUM => 0x00000002,
385 ALLOW_BAREKEY => 0x00000004,
386 ALLOW_SINGLEQUOTE => 0x00000008,
387 EXPANDED => 0x20000000, # for developer's
394 *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"};
395 *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"};
396 *{"JSON::XS::is_xs"} = sub { 1 };
397 *{"JSON::XS::is_pp"} = sub { 0 };
403 my ($class, @methods) = @_;
408 push @JSON::Backend::XS::Supportable::ISA, 'JSON';
410 my $pkg = 'JSON::Backend::XS::Supportable';
413 my $proto = new JSON::XS; $$proto = 0;
417 for my $method (@methods) {
418 my $flag = uc($method);
419 my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0);
420 $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0);
424 $pkg->_make_unsupported_method($method => $type);
427 push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
428 push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
430 $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
439 # Helper classes for XS
442 package JSON::Backend::XS::Supportable;
445 my $JSON_XS_encode_orignal = \&JSON::XS::encode;
446 my $JSON_XS_decode_orignal = \&JSON::XS::decode;
448 $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
450 sub _make_unsupported_method {
451 my ($pkg, $method, $type) = @_;
456 *{"$pkg\::$method"} = sub {
458 if (defined $_[1] ? $_[1] : 1) {
466 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
467 *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode;
470 *JSON::XS::encode = $JSON_XS_encode_orignal;
471 *JSON::XS::decode = $JSON_XS_decode_orignal;
477 *{"$pkg\::get_$method"} = sub {
478 ${$_[0]} & $type ? 1 : '';
487 my $pp = new JSON::PP;
488 my $prop = $_[0]->property;
490 for my $name (keys %$prop) {
491 $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
494 my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
495 : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
496 my $flags = ${$_[0]} || 0;
498 for my $name (keys %$unsupported) {
499 next if ($name eq 'EXPANDED'); # for developer's
500 my $enable = ($flags & $unsupported->{$name}) ? 1 : 0;
501 my $method = lc $name;
502 $pp->$method($enable);
505 $pp->indent_length( $_[0]->get_indent_length );
511 sub _encode { # using with PP encod
512 _set_for_pp('encode' => @_)->encode($_[1]);
516 sub _decode { # if unsupported-flag is set, use PP
517 _set_for_pp('decode' => @_)->decode($_[1]);
521 sub decode_prefix { # if unsupported-flag is set, use PP
522 _set_for_pp('decode' => @_)->decode_prefix($_[1]);
526 sub get_indent_length {
534 if (!defined $length or $length > 15 or $length < 0) {
535 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
540 ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
542 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
554 JSON - JSON (JavaScript Object Notation) encoder/decoder
558 use JSON; # imports encode_json, decode_json, to_json and from_json.
560 $json_text = to_json($perl_scalar);
561 $perl_scalar = from_json($json_text);
564 $json_text = to_json($perl_scalar, {ascii => 1});
565 $perl_scalar = from_json($json_text, {utf8 => 1});
570 $json_text = $json->encode($perl_scalar);
571 $perl_scalar = $json->decode($json_text);
574 $json_text = $json->pretty->encode($perl_scalar);
577 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
578 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
581 # If you want to use PP only support features, call with '-support_by_pp'
582 # When XS unsupported feature is enable, using PP de/encode.
584 use JSON -support_by_pp;
591 This version is compatible with JSON::XS B<2.26> and later.
596 ************************** CAUTION ********************************
597 * This is 'JSON module version 2' and there are many differences *
599 * Please check your applications useing old version. *
600 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
601 *******************************************************************
603 JSON (JavaScript Object Notation) is a simple data format.
604 See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
606 This module converts Perl data structures to JSON and vice versa using either
607 L<JSON::XS> or L<JSON::PP>.
609 JSON::XS is the fastest and most proper JSON module on CPAN which must be
610 compiled and installed in your environment.
611 JSON::PP is a pure-Perl module which is bundled in this distribution and
612 has a strong compatibility to JSON::XS.
614 This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
615 So its features completely depend on JSON::XS or JSON::PP.
617 See to L<BACKEND MODULE DECISION>.
619 To distinguish the module name 'JSON' and the format type JSON,
620 the former is quoted by CE<lt>E<gt> (its results vary with your using media),
621 and the latter is left just as it is.
623 Module name : C<JSON>
631 =item * correct unicode handling
633 This module (i.e. backend modules) knows how to handle Unicode, documents
634 how and when it does so, and even documents what "correct" means.
636 Even though there are limitations, this feature is available since Perl version 5.6.
638 JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
639 C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005.
641 With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
642 JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
643 See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
645 See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
646 and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
649 =item * round-trip integrity
651 When you serialise a perl data structure using only data types supported by JSON,
652 the deserialised data structure is identical on the Perl level.
653 (e.g. the string "2.0" doesn't suddenly become "2" just because it looks
654 like a number). There minor I<are> exceptions to this, read the MAPPING
655 section below to learn about those.
657 =item * strict checking of JSON correctness
659 There is no guessing, no generating of illegal JSON texts by default,
660 and only JSON is accepted as input by default (the latter is a security
663 See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
667 This module returns a JSON::XS object itself if avaliable.
668 Compared to other JSON modules and other serialisers such as Storable,
669 JSON::XS usually compares favourably in terms of speed, too.
671 If not avaliable, C<JSON> returns a JSON::PP object instead of JSON::XS and
672 it is very slow as pure-Perl.
674 =item * simple to use
676 This module has both a simple functional interface as well as an
677 object oriented interface interface.
679 =item * reasonably versatile output formats
681 You can choose between the most compact guaranteed-single-line format possible
682 (nice for simple line-based protocols), a pure-ASCII format (for when your transport
683 is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
684 format (for when you want to read that stuff). Or you can combine those features
685 in whatever way you like.
689 =head1 FUNCTIONAL INTERFACE
691 Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
692 C<to_json> and C<from_json> are additional functions.
696 $json_text = to_json($perl_scalar)
698 Converts the given Perl data structure to a json string.
700 This function call is functionally identical to:
702 $json_text = JSON->new->encode($perl_scalar)
704 Takes a hash reference as the second.
706 $json_text = to_json($perl_scalar, $flag_hashref)
710 $json_text = encode_json($perl_scalar, {utf8 => 1, pretty => 1})
714 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
719 $perl_scalar = from_json($json_text)
721 The opposite of C<to_json>: expects a json string and tries
722 to parse it, returning the resulting reference.
724 This function call is functionally identical to:
726 $perl_scalar = JSON->decode($json_text)
728 Takes a hash reference as the second.
730 $perl_scalar = from_json($json_text, $flag_hashref)
734 $perl_scalar = from_json($json_text, {utf8 => 1})
738 $perl_scalar = JSON->new->utf8(1)->decode($json_text)
742 $json_text = encode_json $perl_scalar
744 Converts the given Perl data structure to a UTF-8 encoded, binary string.
746 This function call is functionally identical to:
748 $json_text = JSON->new->utf8->encode($perl_scalar)
752 $perl_scalar = decode_json $json_text
754 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
755 to parse that as an UTF-8 encoded JSON text, returning the resulting
758 This function call is functionally identical to:
760 $perl_scalar = JSON->new->utf8->decode($json_text)
764 $is_boolean = JSON::is_bool($scalar)
766 Returns true if the passed scalar represents either JSON::true or
767 JSON::false, two constants that act like C<1> and C<0> respectively
768 and are also used to represent JSON C<true> and C<false> in Perl strings.
772 Returns JSON true value which is blessed object.
773 It C<isa> JSON::Boolean object.
777 Returns JSON false value which is blessed object.
778 It C<isa> JSON::Boolean object.
784 See L<MAPPING>, below, for more information on how JSON values are mapped to
787 =head1 COMMON OBJECT-ORIENTED INTERFACE
794 Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
795 that can be used to de/encode JSON strings.
797 All boolean flags described below are by default I<disabled>.
799 The mutators for flags all return the JSON object again and thus calls can
802 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
807 $json = $json->ascii([$enable])
809 $enabled = $json->get_ascii
811 If $enable is true (or missing), then the encode method will not generate characters outside
812 the code range 0..127. Any Unicode characters outside that range will be escaped using either
813 a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
815 If $enable is false, then the encode method will not escape Unicode characters unless
816 required by the JSON syntax or other flags. This results in a faster and more compact format.
818 This feature depends on the used Perl version and environment.
820 See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
822 JSON->new->ascii(1)->encode([chr 0x10401])
827 $json = $json->latin1([$enable])
829 $enabled = $json->get_latin1
831 If $enable is true (or missing), then the encode method will encode the resulting JSON
832 text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
834 If $enable is false, then the encode method will not escape Unicode characters
835 unless required by the JSON syntax or other flags.
837 JSON->new->latin1->encode (["\x{89}\x{abc}"]
838 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
842 $json = $json->utf8([$enable])
844 $enabled = $json->get_utf8
846 If $enable is true (or missing), then the encode method will encode the JSON result
847 into UTF-8, as required by many protocols, while the decode method expects to be handled
848 an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
849 characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
851 In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
852 encoding families, as described in RFC4627.
854 If $enable is false, then the encode method will return the JSON string as a (non-encoded)
855 Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
856 (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
859 Example, output UTF-16BE-encoded JSON:
862 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
864 Example, decode UTF-32LE-encoded JSON:
867 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
869 See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
874 $json = $json->pretty([$enable])
876 This enables (or disables) all of the C<indent>, C<space_before> and
877 C<space_after> (and in the future possibly more) flags in one call to
878 generate the most readable (or most compact) form possible.
882 $json->indent->space_before->space_after
884 The indent space length is three and JSON::XS cannot change the indent
889 $json = $json->indent([$enable])
891 $enabled = $json->get_indent
893 If C<$enable> is true (or missing), then the C<encode> method will use a multiline
894 format as output, putting every array member or object/hash key-value pair
895 into its own line, identing them properly.
897 If C<$enable> is false, no newlines or indenting will be produced, and the
898 resulting JSON text is guarenteed not to contain any C<newlines>.
900 This setting has no effect when decoding JSON texts.
902 The indent space length is three.
903 With JSON::PP, you can also access C<indent_length> to change indent space length.
908 $json = $json->space_before([$enable])
910 $enabled = $json->get_space_before
912 If C<$enable> is true (or missing), then the C<encode> method will add an extra
913 optional space before the C<:> separating keys from values in JSON objects.
915 If C<$enable> is false, then the C<encode> method will not add any extra
916 space at those places.
918 This setting has no effect when decoding JSON texts.
920 Example, space_before enabled, space_after and indent disabled:
927 $json = $json->space_after([$enable])
929 $enabled = $json->get_space_after
931 If C<$enable> is true (or missing), then the C<encode> method will add an extra
932 optional space after the C<:> separating keys from values in JSON objects
933 and extra whitespace after the C<,> separating key-value pairs and array
936 If C<$enable> is false, then the C<encode> method will not add any extra
937 space at those places.
939 This setting has no effect when decoding JSON texts.
941 Example, space_before and indent disabled, space_after enabled:
948 $json = $json->relaxed([$enable])
950 $enabled = $json->get_relaxed
952 If C<$enable> is true (or missing), then C<decode> will accept some
953 extensions to normal JSON syntax (see below). C<encode> will not be
954 affected in anyway. I<Be aware that this option makes you accept invalid
955 JSON texts as if they were valid!>. I suggest only to use this option to
956 parse application-specific files written by humans (configuration files,
959 If C<$enable> is false (the default), then C<decode> will only accept
962 Currently accepted extensions are:
966 =item * list items can have an end-comma
968 JSON I<separates> array elements and key-value pairs with commas. This
969 can be annoying if you write JSON texts manually and want to be able to
970 quickly append elements, so this extension accepts comma at the end of
971 such items not just between them:
975 2, <- this comma not normally allowed
979 "k2": "v2", <- this comma not normally allowed
982 =item * shell-style '#'-comments
984 Whenever JSON allows whitespace, shell-style comments are additionally
985 allowed. They are terminated by the first carriage-return or line-feed
986 character, after which more white-space and comments are allowed.
989 1, # this comment not allowed in JSON
990 # neither this one...
998 $json = $json->canonical([$enable])
1000 $enabled = $json->get_canonical
1002 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
1003 by sorting their keys. This is adding a comparatively high overhead.
1005 If C<$enable> is false, then the C<encode> method will output key-value
1006 pairs in the order Perl stores them (which will likely change between runs
1007 of the same script).
1009 This option is useful if you want the same data structure to be encoded as
1010 the same JSON text (given the same overall settings). If it is disabled,
1011 the same hash might be encoded differently even if contains the same data,
1012 as key-value pairs have no inherent ordering in Perl.
1014 This setting has no effect when decoding JSON texts.
1018 $json = $json->allow_nonref([$enable])
1020 $enabled = $json->get_allow_nonref
1022 If C<$enable> is true (or missing), then the C<encode> method can convert a
1023 non-reference into its corresponding string, number or null JSON value,
1024 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
1025 values instead of croaking.
1027 If C<$enable> is false, then the C<encode> method will croak if it isn't
1028 passed an arrayref or hashref, as JSON texts must either be an object
1029 or array. Likewise, C<decode> will croak if given something that is not a
1030 JSON object or array.
1032 JSON->new->allow_nonref->encode ("Hello, World!")
1035 =head2 allow_unknown
1037 $json = $json->allow_unknown ([$enable])
1039 $enabled = $json->get_allow_unknown
1041 If $enable is true (or missing), then "encode" will *not* throw an
1042 exception when it encounters values it cannot represent in JSON (for
1043 example, filehandles) but instead will encode a JSON "null" value.
1044 Note that blessed objects are not included here and are handled
1045 separately by c<allow_nonref>.
1047 If $enable is false (the default), then "encode" will throw an
1048 exception when it encounters anything it cannot encode as JSON.
1050 This option does not affect "decode" in any way, and it is
1051 recommended to leave it off unless you know your communications
1054 =head2 allow_blessed
1056 $json = $json->allow_blessed([$enable])
1058 $enabled = $json->get_allow_blessed
1060 If C<$enable> is true (or missing), then the C<encode> method will not
1061 barf when it encounters a blessed reference. Instead, the value of the
1062 B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
1063 disabled or no C<TO_JSON> method found) or a representation of the
1064 object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
1065 encoded. Has no effect on C<decode>.
1067 If C<$enable> is false (the default), then C<encode> will throw an
1068 exception when it encounters a blessed object.
1071 =head2 convert_blessed
1073 $json = $json->convert_blessed([$enable])
1075 $enabled = $json->get_convert_blessed
1077 If C<$enable> is true (or missing), then C<encode>, upon encountering a
1078 blessed object, will check for the availability of the C<TO_JSON> method
1079 on the object's class. If found, it will be called in scalar context
1080 and the resulting scalar will be encoded instead of the object. If no
1081 C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
1084 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
1085 returns other blessed objects, those will be handled in the same
1086 way. C<TO_JSON> must take care of not causing an endless recursion cycle
1087 (== crash) in this case. The name of C<TO_JSON> was chosen because other
1088 methods called by the Perl core (== not by the user of the object) are
1089 usually in upper case letters and to avoid collisions with the C<to_json>
1092 This setting does not yet influence C<decode> in any way.
1094 If C<$enable> is false, then the C<allow_blessed> setting will decide what
1095 to do when a blessed object is found.
1099 =item convert_blessed_universally mode
1101 If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
1102 subroutine is defined as the below code:
1104 *UNIVERSAL::TO_JSON = sub {
1105 my $b_obj = B::svref_2object( $_[0] );
1106 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
1107 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
1112 This will cause that C<encode> method converts simple blessed objects into
1113 JSON objects as non-blessed object.
1115 JSON -convert_blessed_universally;
1116 $json->allow_blessed->convert_blessed->encode( $blessed_object )
1118 This feature is experimental and may be removed in the future.
1122 =head2 filter_json_object
1124 $json = $json->filter_json_object([$coderef])
1126 When C<$coderef> is specified, it will be called from C<decode> each
1127 time it decodes a JSON object. The only argument passed to the coderef
1128 is a reference to the newly-created hash. If the code references returns
1129 a single scalar (which need not be a reference), this value
1130 (i.e. a copy of that scalar to avoid aliasing) is inserted into the
1131 deserialised data structure. If it returns an empty list
1132 (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
1133 hash will be inserted. This setting can slow down decoding considerably.
1135 When C<$coderef> is omitted or undefined, any existing callback will
1136 be removed and C<decode> will not change the deserialised hash in any
1139 Example, convert all JSON objects into the integer 5:
1141 my $js = JSON->new->filter_json_object (sub { 5 });
1143 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
1144 # throw an exception because allow_nonref is not enabled
1145 # so a lone 5 is not allowed.
1146 $js->decode ('{"a":1, "b":2}');
1149 =head2 filter_json_single_key_object
1151 $json = $json->filter_json_single_key_object($key [=> $coderef])
1153 Works remotely similar to C<filter_json_object>, but is only called for
1154 JSON objects having a single key named C<$key>.
1156 This C<$coderef> is called before the one specified via
1157 C<filter_json_object>, if any. It gets passed the single value in the JSON
1158 object. If it returns a single value, it will be inserted into the data
1159 structure. If it returns nothing (not even C<undef> but the empty list),
1160 the callback from C<filter_json_object> will be called next, as if no
1161 single-key callback were specified.
1163 If C<$coderef> is omitted or undefined, the corresponding callback will be
1164 disabled. There can only ever be one callback for a given key.
1166 As this callback gets called less often then the C<filter_json_object>
1167 one, decoding speed will not usually suffer as much. Therefore, single-key
1168 objects make excellent targets to serialise Perl objects into, especially
1169 as single-key JSON objects are as close to the type-tagged value concept
1170 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
1171 support this in any way, so you need to make sure your data never looks
1172 like a serialised Perl hash.
1174 Typical names for the single object key are C<__class_whatever__>, or
1175 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
1176 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
1179 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
1180 into the corresponding C<< $WIDGET{<id>} >> object:
1182 # return whatever is in $WIDGET{5}:
1185 ->filter_json_single_key_object (__widget__ => sub {
1188 ->decode ('{"__widget__": 5')
1190 # this can be used with a TO_JSON method in some "widget" class
1191 # for serialisation to json:
1192 sub WidgetBase::TO_JSON {
1195 unless ($self->{id}) {
1196 $self->{id} = ..get..some..id..;
1197 $WIDGET{$self->{id}} = $self;
1200 { __widget__ => $self->{id} }
1206 $json = $json->shrink([$enable])
1208 $enabled = $json->get_shrink
1210 With JSON::XS, this flag resizes strings generated by either
1211 C<encode> or C<decode> to their minimum size possible. This can save
1212 memory when your JSON texts are either very very long or you have many
1213 short strings. It will also try to downgrade any strings to octet-form
1214 if possible: perl stores strings internally either in an encoding called
1215 UTF-X or in octet-form. The latter cannot store everything but uses less
1216 space in general (and some buggy Perl or C code might even rely on that
1217 internal representation being used).
1219 With JSON::PP, it is noop about resizing strings but tries
1220 C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
1222 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
1226 $json = $json->max_depth([$maximum_nesting_depth])
1228 $max_depth = $json->get_max_depth
1230 Sets the maximum nesting level (default C<512>) accepted while encoding
1231 or decoding. If a higher nesting level is detected in JSON text or a Perl
1232 data structure, then the encoder and decoder will stop and croak at that
1235 Nesting level is defined by number of hash- or arrayrefs that the encoder
1236 needs to traverse to reach a given point or the number of C<{> or C<[>
1237 characters without their matching closing parenthesis crossed to reach a
1238 given character in a string.
1240 If no argument is given, the highest possible setting will be used, which
1243 Note that nesting is implemented by recursion in C. The default value has
1244 been chosen to be as large as typical operating systems allow without
1245 crashing. (JSON::XS)
1247 With JSON::PP as the backend, when a large value (100 or more) was set and
1248 it de/encodes a deep nested object/text, it may raise a warning
1249 'Deep recursion on subroutin' at the perl runtime phase.
1251 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1255 $json = $json->max_size([$maximum_string_size])
1257 $max_size = $json->get_max_size
1259 Set the maximum length a JSON text may have (in bytes) where decoding is
1260 being attempted. The default is C<0>, meaning no limit. When C<decode>
1261 is called on a string that is longer then this many bytes, it will not
1262 attempt to decode the string but throw an exception. This setting has no
1263 effect on C<encode> (yet).
1265 If no argument is given, the limit check will be deactivated (same as when
1268 See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
1272 $json_text = $json->encode($perl_scalar)
1274 Converts the given Perl data structure (a simple scalar or a reference
1275 to a hash or array) to its JSON representation. Simple scalars will be
1276 converted into JSON string or number sequences, while references to arrays
1277 become JSON arrays and references to hashes become JSON objects. Undefined
1278 Perl values (e.g. C<undef>) become JSON C<null> values.
1279 References to the integers C<0> and C<1> are converted into C<true> and C<false>.
1283 $perl_scalar = $json->decode($json_text)
1285 The opposite of C<encode>: expects a JSON text and tries to parse it,
1286 returning the resulting simple scalar or reference. Croaks on error.
1288 JSON numbers and strings become simple Perl scalars. JSON arrays become
1289 Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
1290 C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
1291 C<null> becomes C<undef>.
1293 =head2 decode_prefix
1295 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
1297 This works like the C<decode> method, but instead of raising an exception
1298 when there is trailing garbage after the first JSON object, it will
1299 silently stop parsing there and return the number of characters consumed
1302 JSON->new->decode_prefix ("[1] the tail")
1305 See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
1309 $boolean = $json->property($property_name)
1311 Returns a boolean value about above some properties.
1313 The available properties are C<ascii>, C<latin1>, C<utf8>,
1314 C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
1315 C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
1316 C<shrink>, C<max_depth> and C<max_size>.
1318 $boolean = $json->property('utf8');
1321 $boolean = $json->property('utf8');
1324 Sets the propery with a given boolean value.
1326 $json = $json->property($property_name => $boolean);
1328 With no argumnt, it returns all the above properties as a hash reference.
1330 $flag_hashref = $json->property();
1332 =head1 INCREMENTAL PARSING
1334 In JSON::XS 2.2, incremental parsing feature of JSON texts was implemented.
1335 Please check to L<JSON::XS/INCREMENTAL PARSING>.
1339 =item [void, scalar or list context] = $json->incr_parse ([$string])
1341 This is the central parsing function. It can both append new text and
1342 extract objects from the stream accumulated so far (both of these
1343 functions are optional).
1345 If C<$string> is given, then this string is appended to the already
1346 existing JSON fragment stored in the C<$json> object.
1348 After that, if the function is called in void context, it will simply
1349 return without doing anything further. This can be used to add more text
1350 in as many chunks as you want.
1352 If the method is called in scalar context, then it will try to extract
1353 exactly I<one> JSON object. If that is successful, it will return this
1354 object, otherwise it will return C<undef>. If there is a parse error,
1355 this method will croak just as C<decode> would do (one can then use
1356 C<incr_skip> to skip the errornous part). This is the most common way of
1359 And finally, in list context, it will try to extract as many objects
1360 from the stream as it can find and return them, or the empty list
1361 otherwise. For this to work, there must be no separators between the JSON
1362 objects or arrays, instead they must be concatenated back-to-back. If
1363 an error occurs, an exception will be raised as in the scalar context
1364 case. Note that in this case, any previously-parsed JSON texts will be
1367 =item $lvalue_string = $json->incr_text
1369 This method returns the currently stored JSON fragment as an lvalue, that
1370 is, you can manipulate it. This I<only> works when a preceding call to
1371 C<incr_parse> in I<scalar context> successfully returned an object. Under
1372 all other circumstances you must not call this function (I mean it.
1373 although in simple tests it might actually work, it I<will> fail under
1374 real world conditions). As a special exception, you can also call this
1375 method before having parsed anything.
1377 This function is useful in two cases: a) finding the trailing text after a
1378 JSON object or b) parsing multiple JSON objects separated by non-JSON text
1381 In Perl 5.005, C<lvalue> attribute is not available.
1382 You must write codes like the below:
1384 $string = $json->incr_text;
1385 $string =~ s/\s*,\s*//;
1386 $json->incr_text( $string );
1388 =item $json->incr_skip
1390 This will reset the state of the incremental parser and will remove the
1391 parsed text from the input buffer. This is useful after C<incr_parse>
1392 died, in which case the input buffer and incremental parser state is left
1393 unchanged, to skip the text parsed so far and to reset the parse state.
1395 =item $json->incr_reset
1397 This completely resets the incremental parser, that is, after this call,
1398 it will be as if the parser had never parsed anything.
1400 This is useful if you want ot repeatedly parse JSON objects and want to
1401 ignore any trailing data, which means you have to reset the parser after
1402 each successful decode.
1406 =head1 JSON::PP SUPPORT METHODS
1408 The below methods are JSON::PP own methods, so when C<JSON> works
1409 with JSON::PP (i.e. the created object is a JSON::PP object), available.
1410 See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
1412 If you use C<JSON> with additonal C<-support_by_pp>, some methods
1413 are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
1415 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
1417 use JSON -support_by_pp;
1419 my $json = new JSON;
1420 $json->allow_nonref->escape_slash->encode("/");
1422 # functional interfaces too.
1423 print to_json(["/"], {escape_slash => 1});
1424 print from_json('["foo"]', {utf8 => 1});
1426 If you do not want to all functions but C<-support_by_pp>,
1429 use JSON -support_by_pp, -no_export;
1430 # functional interfaces are not exported.
1432 =head2 allow_singlequote
1434 $json = $json->allow_singlequote([$enable])
1436 If C<$enable> is true (or missing), then C<decode> will accept
1437 any JSON strings quoted by single quotations that are invalid JSON
1440 $json->allow_singlequote->decode({"foo":'bar'});
1441 $json->allow_singlequote->decode({'foo':"bar"});
1442 $json->allow_singlequote->decode({'foo':'bar'});
1444 As same as the C<relaxed> option, this option may be used to parse
1445 application-specific files written by humans.
1447 =head2 allow_barekey
1449 $json = $json->allow_barekey([$enable])
1451 If C<$enable> is true (or missing), then C<decode> will accept
1452 bare keys of JSON object that are invalid JSON format.
1454 As same as the C<relaxed> option, this option may be used to parse
1455 application-specific files written by humans.
1457 $json->allow_barekey->decode('{foo:"bar"}');
1461 $json = $json->allow_bignum([$enable])
1463 If C<$enable> is true (or missing), then C<decode> will convert
1464 the big integer Perl cannot handle as integer into a L<Math::BigInt>
1465 object and convert a floating number (any) into a L<Math::BigFloat>.
1467 On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1468 objects into JSON numbers with C<allow_blessed> enable.
1470 $json->allow_nonref->allow_blessed->allow_bignum;
1471 $bigfloat = $json->decode('2.000000000000000000000000001');
1472 print $json->encode($bigfloat);
1473 # => 2.000000000000000000000000001
1475 See to L<MAPPING> aboout the conversion of JSON number.
1479 $json = $json->loose([$enable])
1481 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
1482 and the module doesn't allow to C<decode> to these (except for \x2f).
1483 If C<$enable> is true (or missing), then C<decode> will accept these
1486 $json->loose->decode(qq|["abc
1489 See to L<JSON::PP/JSON::PP OWN METHODS>.
1493 $json = $json->escape_slash([$enable])
1495 According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
1496 JSON backend modules encode strings without escaping slash.
1498 If C<$enable> is true (or missing), then C<encode> will escape slashes.
1500 =head2 indent_length
1502 $json = $json->indent_length($length)
1504 With JSON::XS, The indent space length is 3 and cannot be changed.
1505 With JSON::PP, it sets the indent space length with the given $length.
1506 The default is 3. The acceptable range is 0 to 15.
1510 $json = $json->sort_by($function_name)
1511 $json = $json->sort_by($subroutine_ref)
1513 If $function_name or $subroutine_ref are set, its sort routine are used.
1515 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
1516 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1518 $js = $pc->sort_by('own_sort')->encode($obj);
1519 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1521 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
1523 As the sorting routine runs in the JSON::PP scope, the given
1524 subroutine name and the special variables C<$a>, C<$b> will begin
1527 If $integer is set, then the effect is same as C<canonical> on.
1529 See to L<JSON::PP/JSON::PP OWN METHODS>.
1533 This section is copied from JSON::XS and modified to C<JSON>.
1534 JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
1536 See to L<JSON::XS/MAPPING>.
1544 A JSON object becomes a reference to a hash in Perl. No ordering of object
1545 keys is preserved (JSON does not preserver object key ordering itself).
1549 A JSON array becomes a reference to an array in Perl.
1553 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1554 are represented by the same codepoints in the Perl string, so no manual
1555 decoding is necessary.
1559 A JSON number becomes either an integer, numeric (floating point) or
1560 string scalar in perl, depending on its range and any fractional parts. On
1561 the Perl level, there is no difference between those as Perl handles all
1562 the conversion details, but an integer may take slightly less memory and
1563 might represent more values exactly than floating point numbers.
1565 If the number consists of digits only, C<JSON> will try to represent
1566 it as an integer value. If that fails, it will try to represent it as
1567 a numeric (floating point) value if that is possible without loss of
1568 precision. Otherwise it will preserve the number as a string value (in
1569 which case you lose roundtripping ability, as the JSON number will be
1570 re-encoded toa JSON string).
1572 Numbers containing a fractional or exponential part will always be
1573 represented as numeric (floating point) values, possibly at a loss of
1574 precision (in which case you might lose perfect roundtripping ability, but
1575 the JSON number will still be re-encoded as a JSON number).
1577 If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
1578 and the numeric can be optionally converted into L<Math::BigInt> and
1579 L<Math::BigFloat> objects.
1583 These JSON atoms become C<JSON::true> and C<JSON::false>,
1584 respectively. They are overloaded to act almost exactly like the numbers
1585 C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
1586 the C<JSON::is_bool> function.
1588 If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
1589 they represent as C<true> and C<false> respectively.
1591 print JSON::true . "\n";
1593 print JSON::true + 1;
1596 ok(JSON::true eq 'true');
1597 ok(JSON::true eq '1');
1598 ok(JSON::true == 1);
1600 C<JSON> will install these missing overloading features to the backend modules.
1605 A JSON null atom becomes C<undef> in Perl.
1607 C<JSON::null> returns C<unddef>.
1614 The mapping from Perl to JSON is slightly more difficult, as Perl is a
1615 truly typeless language, so we can only guess which JSON type is meant by
1620 =item hash references
1622 Perl hash references become JSON objects. As there is no inherent ordering
1623 in hash keys (or JSON objects), they will usually be encoded in a
1624 pseudo-random order that can change between runs of the same program but
1625 stays generally the same within a single run of a program. C<JSON>
1626 optionally sort the hash keys (determined by the I<canonical> flag), so
1627 the same datastructure will serialise to the same JSON text (given same
1628 settings and version of JSON::XS), but this incurs a runtime overhead
1629 and is only rarely useful, e.g. when you want to compare some JSON text
1630 against another for equality.
1632 In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
1635 =item array references
1637 Perl array references become JSON arrays.
1639 =item other references
1641 Other unblessed references are generally not allowed and will cause an
1642 exception to be thrown, except for references to the integers C<0> and
1643 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1644 also use C<JSON::false> and C<JSON::true> to improve readability.
1646 to_json [\0,JSON::true] # yields [false,true]
1648 =item JSON::true, JSON::false, JSON::null
1650 These special values become JSON true and JSON false values,
1651 respectively. You can also use C<\1> and C<\0> directly if you want.
1653 JSON::null returns C<undef>.
1655 =item blessed objects
1657 Blessed objects are not directly representable in JSON. See the
1658 C<allow_blessed> and C<convert_blessed> methods on various options on
1659 how to deal with this: basically, you can choose between throwing an
1660 exception, encoding the reference as if it weren't blessed, or provide
1661 your own serialiser method.
1663 With C<convert_blessed_universally> mode, C<encode> converts blessed
1664 hash references or blessed array references (contains other blessed references)
1665 into JSON members and arrays.
1667 use JSON -convert_blessed_universally;
1668 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
1670 See to L<convert_blessed>.
1672 =item simple scalars
1674 Simple Perl scalars (any scalar that is not a reference) are the most
1675 difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
1676 JSON C<null> values, scalars that have last been used in a string context
1677 before encoding as JSON strings, and anything else as number value:
1680 encode_json [2] # yields [2]
1681 encode_json [-3.0e17] # yields [-3e+17]
1682 my $value = 5; encode_json [$value] # yields [5]
1684 # used as string, so dump as string
1686 encode_json [$value] # yields ["5"]
1688 # undef becomes null
1689 encode_json [undef] # yields [null]
1691 You can force the type to be a string by stringifying it:
1693 my $x = 3.1; # some variable containing a number
1695 $x .= ""; # another, more awkward way to stringify
1696 print $x; # perl does it for you, too, quite often
1698 You can force the type to be a number by numifying it:
1700 my $x = "3"; # some variable containing a string
1701 $x += 0; # numify it, ensuring it will be dumped as a number
1702 $x *= 1; # same thing, the choise is yours.
1704 You can not currently force the type in other, less obscure, ways.
1708 If the backend is JSON::PP and C<allow_bignum> is enable,
1709 C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1710 objects into JSON numbers.
1715 =head1 JSON and ECMAscript
1717 See to L<JSON::XS/JSON and ECMAscript>.
1719 =head1 JSON and YAML
1721 JSON is not a subset of YAML.
1722 See to L<JSON::XS/JSON and YAML>.
1725 =head1 BACKEND MODULE DECISION
1727 When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
1728 C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
1730 The C<JSON> constructor method returns an object inherited from the backend module,
1731 and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash
1734 So, your program should not depend on the backend module, especially
1735 returned objects should not be modified.
1737 my $json = JSON->new; # XS or PP?
1738 $json->{stash} = 'this is xs object'; # this code may raise an error!
1740 To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
1742 JSON->backend; # 'JSON::XS' or 'JSON::PP'
1744 JSON->backend->is_pp: # 0 or 1
1746 JSON->backend->is_xs: # 1 or 0
1748 $json->is_xs; # 1 or 0
1750 $json->is_pp; # 0 or 1
1753 If you set an enviornment variable C<PERL_JSON_BACKEND>, The calling action will be changed.
1757 =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
1761 =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
1763 (The default) Use compiled JSON::XS if it is properly compiled & installed,
1764 otherwise use JSON::PP.
1766 =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
1768 Always use compiled JSON::XS, die if it isn't properly compiled & installed.
1772 These ideas come from L<DBI::PurePerl> mechanism.
1776 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
1777 use JSON; # always uses JSON::PP
1779 In future, it may be able to specify another module.
1781 =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
1783 Many methods are available with either JSON::XS or JSON::PP and
1784 when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported)
1785 method is called, it will C<warn> and be noop.
1787 But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
1788 it makes a part of those unupported methods available.
1789 This feature is achieved by using JSON::PP in C<de/encode>.
1791 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
1792 use JSON -support_by_pp;
1793 my $json = new JSON;
1794 $json->allow_nonref->escape_slash->encode("/");
1796 At this time, the returned object is a C<JSON::Backend::XS::Supportable>
1797 object (re-blessed XS object), and by checking JSON::XS unsupported flags
1798 in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
1799 C<allow_barekey>, C<allow_singlequote>, C<escape_slash>, C<as_nonblessed>
1800 and C<indent_length>.
1802 When any unsupported methods are not enable, C<XS de/encode> will be
1803 used as is. The switch is achieved by changing the symbolic tables.
1805 C<-support_by_pp> is effective only when the backend module is JSON::XS
1806 and it makes the de/encoding speed down a bit.
1808 See to L<JSON::PP SUPPORT METHODS>.
1810 =head1 INCOMPATIBLE CHANGES TO OLD VERSION
1812 There are big incompatibility between new version (2.00) and old (1.xx).
1813 If you use old C<JSON> 1.xx in your code, please check it.
1815 See to L<Transition ways from 1.xx to 2.xx.>
1819 =item jsonToObj and objToJson are obsoleted.
1821 Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
1822 (but not yet deleted from the source).
1823 If you use these functions in your code, please replace them
1824 with C<from_json> and C<to_json>.
1827 =item Global variables are no longer available.
1829 C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
1830 - are not avaliable any longer.
1831 Instead, various features can be used through object methods.
1834 =item Package JSON::Converter and JSON::Parser are deleted.
1836 Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
1838 =item Package JSON::NotString is deleted.
1840 There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
1841 and numbers. It was deleted and replaced by C<JSON::Boolean>.
1843 C<JSON::Boolean> represents C<true> and C<false>.
1845 C<JSON::Boolean> does not represent C<null>.
1847 C<JSON::null> returns C<undef>.
1849 C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
1850 to L<JSON::Boolean>.
1852 =item function JSON::Number is obsoleted.
1854 C<JSON::Number> is now needless because JSON::XS and JSON::PP have
1855 round-trip integrity.
1857 =item JSONRPC modules are deleted.
1859 Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
1860 and C<Apache::JSONRPC > are deleted in this distribution.
1861 Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
1865 =head2 Transition ways from 1.xx to 2.xx.
1867 You should set C<suport_by_pp> mode firstly, because
1868 it is always successful for the below codes even with JSON::XS.
1870 use JSON -support_by_pp;
1874 =item Exported jsonToObj (simple)
1876 from_json($json_text);
1878 =item Exported objToJson (simple)
1880 to_json($perl_scalar);
1882 =item Exported jsonToObj (advanced)
1884 $flags = {allow_barekey => 1, allow_singlequote => 1};
1885 from_json($json_text, $flags);
1890 $JSON::QuotApos = 1;
1891 jsonToObj($json_text);
1893 =item Exported objToJson (advanced)
1895 $flags = {allow_blessed => 1, allow_barekey => 1};
1896 to_json($perl_scalar, $flags);
1901 objToJson($perl_scalar);
1903 =item jsonToObj as object method
1905 $json->decode($json_text);
1907 =item objToJson as object method
1909 $json->encode($perl_scalar);
1911 =item new method with parameters
1913 The C<new> method in 2.x takes any parameters no longer.
1914 You can set parameters instead;
1916 $json = JSON->new->pretty;
1918 =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
1920 If C<indent> is enable, that menas C<$JSON::Pretty> flag set. And
1921 C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
1924 $json->indent->space_before->space_after;
1930 To change indent length, use C<indent_length>.
1932 (Only with JSON::PP, if C<-support_by_pp> is not used.)
1934 $json->pretty->indent_length(2)->encode($perl_scalar);
1936 =item $JSON::BareKey
1938 (Only with JSON::PP, if C<-support_by_pp> is not used.)
1940 $json->allow_barekey->decode($json_text)
1942 =item $JSON::ConvBlessed
1944 use C<-convert_blessed_universally>. See to L<convert_blessed>.
1946 =item $JSON::QuotApos
1948 (Only with JSON::PP, if C<-support_by_pp> is not used.)
1950 $json->allow_singlequote->decode($json_text)
1952 =item $JSON::SingleQuote
1954 Disable. C<JSON> does not make such a invalid JSON string any longer.
1956 =item $JSON::KeySort
1958 $json->canonical->encode($perl_scalar)
1960 This is the ascii sort.
1962 If you want to use with your own sort routine, check the C<sort_by> method.
1964 (Only with JSON::PP, even if C<-support_by_pp> is used currently.)
1966 $json->sort_by($sort_routine_ref)->encode($perl_scalar)
1968 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
1970 Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
1972 =item $JSON::SkipInvalid
1974 $json->allow_unknown
1976 =item $JSON::AUTOCONVERT
1978 Needless. C<JSON> backend modules have the round-trip integrity.
1982 Needless because C<JSON> (JSON::XS/JSON::PP) sets
1983 the UTF8 flag on properly.
1985 # With UTF8-flagged strings
1987 $json->allow_nonref;
1988 $str = chr(1000); # UTF8-flagged
1990 $json_text = $json->utf8(0)->encode($str);
1991 utf8::is_utf8($json_text);
1993 $json_text = $json->utf8(1)->encode($str);
1994 utf8::is_utf8($json_text);
1997 $str = '"' . chr(1000) . '"'; # UTF8-flagged
1999 $perl_scalar = $json->utf8(0)->decode($str);
2000 utf8::is_utf8($perl_scalar);
2002 $perl_scalar = $json->utf8(1)->decode($str);
2003 # died because of 'Wide character in subroutine'
2005 See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
2007 =item $JSON::UnMapping
2009 Disable. See to L<MAPPING>.
2011 =item $JSON::SelfConvert
2013 This option was deleted.
2014 Instead of it, if a givien blessed object has the C<TO_JSON> method,
2015 C<TO_JSON> will be executed with C<convert_blessed>.
2017 $json->convert_blessed->encode($bleesed_hashref_or_arrayref)
2018 # if need, call allow_blessed
2020 Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
2028 =item example programs
2034 No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
2039 Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
2044 Most of the document is copied and modified from JSON::XS doc.
2046 L<JSON::XS>, L<JSON::PP>
2048 C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
2052 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
2054 JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
2056 The relese of this new version owes to the courtesy of Marc Lehmann.
2059 =head1 COPYRIGHT AND LICENSE
2061 Copyright 2005-2009 by Makamaka Hannyaharamitu
2063 This library is free software; you can redistribute it and/or modify
2064 it under the same terms as Perl itself.