Debian Codegraph @

lib/JSON.pm

raw
1 package JSON;
2
3
4 use strict;
5 use Carp ();
6 use Exporter;
7 BEGIN { @JSON::ISA = 'Exporter' }
8
9 @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
10
11 BEGIN {
12 $JSON::VERSION = '4.10';
13 $JSON::DEBUG = 0 unless (defined $JSON::DEBUG);
14 $JSON::DEBUG = $ENV{ PERL_JSON_DEBUG } if exists $ENV{ PERL_JSON_DEBUG };
15 }
16
17 my %RequiredVersion = (
18 'JSON::PP' => '2.27203',
19 'JSON::XS' => '2.34',
20 );
21
22 # XS and PP common methods
23
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
28 /;
29
30 my @Properties = qw/
31 ascii latin1 utf8 indent space_before space_after relaxed canonical allow_nonref
32 allow_blessed convert_blessed shrink max_depth max_size allow_unknown
33 /;
34
35 my @XSOnlyMethods = qw//; # Currently nothing
36
37 my @PublicMethodsSince4_0 = qw/allow_tags/;
38 my @PropertiesSince4_0 = qw/allow_tags/;
39
40 my @PPOnlyMethods = qw/
41 indent_length sort_by
42 allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed
43 /; # JSON::PP specific
44
45
46 # used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently)
47 my $_INSTALL_DONT_DIE = 1; # When _load_xs fails to load XS, don't die.
48 my $_ALLOW_UNSUPPORTED = 0;
49 my $_UNIV_CONV_BLESSED = 0;
50
51
52 # Check the environment variable to decide worker module.
53
54 unless ($JSON::Backend) {
55 $JSON::DEBUG and Carp::carp("Check used worker module...");
56
57 my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1;
58
59 if ($backend eq '1') {
60 $backend = 'JSON::XS,JSON::PP';
61 }
62 elsif ($backend eq '0') {
63 $backend = 'JSON::PP';
64 }
65 elsif ($backend eq '2') {
66 $backend = 'JSON::XS';
67 }
68 $backend =~ s/\s+//g;
69
70 my @backend_modules = split /,/, $backend;
71 while(my $module = shift @backend_modules) {
72 if ($module =~ /JSON::XS/) {
73 _load_xs($module, @backend_modules ? $_INSTALL_DONT_DIE : 0);
74 }
75 elsif ($module =~ /JSON::PP/) {
76 _load_pp($module);
77 }
78 elsif ($module =~ /JSON::backportPP/) {
79 _load_pp($module);
80 }
81 else {
82 Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid.";
83 }
84 last if $JSON::Backend;
85 }
86 }
87
88
89 sub import {
90 my $pkg = shift;
91 my @what_to_export;
92 my $no_export;
93
94 for my $tag (@_) {
95 if ($tag eq '-support_by_pp') {
96 if (!$_ALLOW_UNSUPPORTED++) {
97 JSON::Backend::XS
98 ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend->is_xs);
99 }
100 next;
101 }
102 elsif ($tag eq '-no_export') {
103 $no_export++, next;
104 }
105 elsif ( $tag eq '-convert_blessed_universally' ) {
106 my $org_encode = $JSON::Backend->can('encode');
107 eval q|
108 require B;
109 local $^W;
110 no strict 'refs';
111 *{"${JSON::Backend}\::encode"} = sub {
112 # only works with Perl 5.18+
113 local *UNIVERSAL::TO_JSON = sub {
114 my $b_obj = B::svref_2object( $_[0] );
115 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
116 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
117 : undef
118 ;
119 };
120 $org_encode->(@_);
121 };
122 | if ( !$_UNIV_CONV_BLESSED++ );
123 next;
124 }
125 push @what_to_export, $tag;
126 }
127
128 return if ($no_export);
129
130 __PACKAGE__->export_to_level(1, $pkg, @what_to_export);
131 }
132
133
134 # OBSOLETED
135
136 sub jsonToObj {
137 my $alternative = 'from_json';
138 if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
139 shift @_; $alternative = 'decode';
140 }
141 Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead.";
142 return JSON::from_json(@_);
143 };
144
145 sub objToJson {
146 my $alternative = 'to_json';
147 if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
148 shift @_; $alternative = 'encode';
149 }
150 Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead.";
151 JSON::to_json(@_);
152 };
153
154
155 # INTERFACES
156
157 sub to_json ($@) {
158 if (
159 ref($_[0]) eq 'JSON'
160 or (@_ > 2 and $_[0] eq 'JSON')
161 ) {
162 Carp::croak "to_json should not be called as a method.";
163 }
164 my $json = JSON->new;
165
166 if (@_ == 2 and ref $_[1] eq 'HASH') {
167 my $opt = $_[1];
168 for my $method (keys %$opt) {
169 $json->$method( $opt->{$method} );
170 }
171 }
172
173 $json->encode($_[0]);
174 }
175
176
177 sub from_json ($@) {
178 if ( ref($_[0]) eq 'JSON' or $_[0] eq 'JSON' ) {
179 Carp::croak "from_json should not be called as a method.";
180 }
181 my $json = JSON->new;
182
183 if (@_ == 2 and ref $_[1] eq 'HASH') {
184 my $opt = $_[1];
185 for my $method (keys %$opt) {
186 $json->$method( $opt->{$method} );
187 }
188 }
189
190 return $json->decode( $_[0] );
191 }
192
193
194
195 sub true { $JSON::true }
196
197 sub false { $JSON::false }
198
199 sub boolean {
200 # might be called as method or as function, so pop() to get the last arg instead of shift() to get the first
201 pop() ? $JSON::true : $JSON::false
202 }
203
204 sub null { undef; }
205
206
207 sub require_xs_version { $RequiredVersion{'JSON::XS'}; }
208
209 sub backend {
210 my $proto = shift;
211 $JSON::Backend;
212 }
213
214 #*module = *backend;
215
216
217 sub is_xs {
218 return $_[0]->backend->is_xs;
219 }
220
221
222 sub is_pp {
223 return $_[0]->backend->is_pp;
224 }
225
226
227 sub pureperl_only_methods { @PPOnlyMethods; }
228
229
230 sub property {
231 my ($self, $name, $value) = @_;
232
233 if (@_ == 1) {
234 my %props;
235 for $name (@Properties) {
236 my $method = 'get_' . $name;
237 if ($name eq 'max_size') {
238 my $value = $self->$method();
239 $props{$name} = $value == 1 ? 0 : $value;
240 next;
241 }
242 $props{$name} = $self->$method();
243 }
244 return \%props;
245 }
246 elsif (@_ > 3) {
247 Carp::croak('property() can take only the option within 2 arguments.');
248 }
249 elsif (@_ == 2) {
250 if ( my $method = $self->can('get_' . $name) ) {
251 if ($name eq 'max_size') {
252 my $value = $self->$method();
253 return $value == 1 ? 0 : $value;
254 }
255 $self->$method();
256 }
257 }
258 else {
259 $self->$name($value);
260 }
261
262 }
263
264
265
266 # INTERNAL
267
268 sub __load_xs {
269 my ($module, $opt) = @_;
270
271 $JSON::DEBUG and Carp::carp "Load $module.";
272 my $required_version = $RequiredVersion{$module} || '';
273
274 eval qq|
275 use $module $required_version ();
276 |;
277
278 if ($@) {
279 if (defined $opt and $opt & $_INSTALL_DONT_DIE) {
280 $JSON::DEBUG and Carp::carp "Can't load $module...($@)";
281 return 0;
282 }
283 Carp::croak $@;
284 }
285 $JSON::BackendModuleXS = $module;
286 return 1;
287 }
288
289 sub _load_xs {
290 my ($module, $opt) = @_;
291 __load_xs($module, $opt) or return;
292
293 my $data = join("", <DATA>); # this code is from Jcode 2.xx.
294 close(DATA);
295 eval $data;
296 JSON::Backend::XS->init($module);
297
298 return 1;
299 };
300
301
302 sub __load_pp {
303 my ($module, $opt) = @_;
304
305 $JSON::DEBUG and Carp::carp "Load $module.";
306 my $required_version = $RequiredVersion{$module} || '';
307
308 eval qq| use $module $required_version () |;
309
310 if ($@) {
311 if ( $module eq 'JSON::PP' ) {
312 $JSON::DEBUG and Carp::carp "Can't load $module ($@), so try to load JSON::backportPP";
313 $module = 'JSON::backportPP';
314 local $^W; # if PP installed but invalid version, backportPP redefines methods.
315 eval qq| require $module |;
316 }
317 Carp::croak $@ if $@;
318 }
319 $JSON::BackendModulePP = $module;
320 return 1;
321 }
322
323 sub _load_pp {
324 my ($module, $opt) = @_;
325 __load_pp($module, $opt);
326
327 JSON::Backend::PP->init($module);
328 };
329
330 #
331 # Helper classes for Backend Module (PP)
332 #
333
334 package JSON::Backend::PP;
335
336 sub init {
337 my ($class, $module) = @_;
338
339 # name may vary, but the module should (always) be a JSON::PP
340
341 local $^W;
342 no strict qw(refs); # this routine may be called after JSON::Backend::XS init was called.
343 *{"JSON::decode_json"} = \&{"JSON::PP::decode_json"};
344 *{"JSON::encode_json"} = \&{"JSON::PP::encode_json"};
345 *{"JSON::is_bool"} = \&{"JSON::PP::is_bool"};
346
347 $JSON::true = ${"JSON::PP::true"};
348 $JSON::false = ${"JSON::PP::false"};
349
350 push @JSON::Backend::PP::ISA, 'JSON::PP';
351 push @JSON::ISA, $class;
352 $JSON::Backend = $class;
353 $JSON::BackendModule = $module;
354 my $version = ${"$class\::VERSION"} = $module->VERSION;
355 $version =~ s/_//;
356 if ($version < 3.99) {
357 push @XSOnlyMethods, qw/allow_tags get_allow_tags/;
358 } else {
359 push @Properties, 'allow_tags';
360 }
361
362 for my $method (@XSOnlyMethods) {
363 *{"JSON::$method"} = sub {
364 Carp::carp("$method is not supported by $module $version.");
365 $_[0];
366 };
367 }
368
369 return 1;
370 }
371
372 sub is_xs { 0 };
373 sub is_pp { 1 };
374
375 #
376 # To save memory, the below lines are read only when XS backend is used.
377 #
378
379 package JSON;
380
381 1;
382 __DATA__
383
384
385 #
386 # Helper classes for Backend Module (XS)
387 #
388
389 package JSON::Backend::XS;
390
391 sub init {
392 my ($class, $module) = @_;
393
394 local $^W;
395 no strict qw(refs);
396 *{"JSON::decode_json"} = \&{"$module\::decode_json"};
397 *{"JSON::encode_json"} = \&{"$module\::encode_json"};
398 *{"JSON::is_bool"} = \&{"$module\::is_bool"};
399
400 $JSON::true = ${"$module\::true"};
401 $JSON::false = ${"$module\::false"};
402
403 push @JSON::Backend::XS::ISA, $module;
404 push @JSON::ISA, $class;
405 $JSON::Backend = $class;
406 $JSON::BackendModule = $module;
407 ${"$class\::VERSION"} = $module->VERSION;
408
409 if ( $module->VERSION < 3 ) {
410 eval 'package JSON::PP::Boolean';
411 push @{"$module\::Boolean::ISA"}, qw(JSON::PP::Boolean);
412 }
413
414 for my $method (@PPOnlyMethods) {
415 *{"JSON::$method"} = sub {
416 Carp::carp("$method is not supported by $module.");
417 $_[0];
418 };
419 }
420
421 return 1;
422 }
423
424 sub is_xs { 1 };
425 sub is_pp { 0 };
426
427 sub support_by_pp {
428 my ($class, @methods) = @_;
429
430 JSON::__load_pp('JSON::PP');
431
432 local $^W;
433 no strict qw(refs);
434
435 for my $method (@methods) {
436 my $pp_method = JSON::PP->can($method) or next;
437 *{"JSON::$method"} = sub {
438 if (!$_[0]->isa('JSON::PP')) {
439 my $xs_self = $_[0];
440 my $pp_self = JSON::PP->new;
441 for (@Properties) {
442 my $getter = "get_$_";
443 $pp_self->$_($xs_self->$getter);
444 }
445 $_[0] = $pp_self;
446 }
447 $pp_method->(@_);
448 };
449 }
450
451 $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
452 }
453
454 1;
455 __END__
456
457 =head1 NAME
458
459 JSON - JSON (JavaScript Object Notation) encoder/decoder
460
461 =head1 SYNOPSIS
462
463 use JSON; # imports encode_json, decode_json, to_json and from_json.
464
465 # simple and fast interfaces (expect/generate UTF-8)
466
467 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
468 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
469
470 # OO-interface
471
472 $json = JSON->new->allow_nonref;
473
474 $json_text = $json->encode( $perl_scalar );
475 $perl_scalar = $json->decode( $json_text );
476
477 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
478
479 =head1 DESCRIPTION
480
481 This module is a thin wrapper for L<JSON::XS>-compatible modules with a few
482 additional features. All the backend modules convert a Perl data structure
483 to a JSON text and vice versa. This module uses L<JSON::XS> by default,
484 and when JSON::XS is not available, falls back on L<JSON::PP>, which is
485 in the Perl core since 5.14. If JSON::PP is not available either, this
486 module then falls back on JSON::backportPP (which is actually JSON::PP
487 in a different .pm file) bundled in the same distribution as this module.
488 You can also explicitly specify to use L<Cpanel::JSON::XS>, a fork of
489 JSON::XS by Reini Urban.
490
491 All these backend modules have slight incompatibilities between them,
492 including extra features that other modules don't support, but as long as you
493 use only common features (most important ones are described below), migration
494 from backend to backend should be reasonably easy. For details, see each
495 backend module you use.
496
497 =head1 CHOOSING BACKEND
498
499 This module respects an environmental variable called C<PERL_JSON_BACKEND>
500 when it decides a backend module to use. If this environmental variable is
501 not set, it tries to load JSON::XS, and if JSON::XS is not available, it
502 falls back on JSON::PP, and then JSON::backportPP if JSON::PP is not available
503 either.
504
505 If you always don't want it to fall back on pure perl modules, set the
506 variable like this (C<export> may be C<setenv>, C<set> and the likes,
507 depending on your environment):
508
509 > export PERL_JSON_BACKEND=JSON::XS
510
511 If you prefer Cpanel::JSON::XS to JSON::XS, then:
512
513 > export PERL_JSON_BACKEND=Cpanel::JSON::XS,JSON::XS,JSON::PP
514
515 You may also want to set this variable at the top of your test files, in order
516 not to be bothered with incompatibilities between backends (you need to wrap
517 this in C<BEGIN>, and set before actually C<use>-ing JSON module, as it decides
518 its backend as soon as it's loaded):
519
520 BEGIN { $ENV{PERL_JSON_BACKEND}='JSON::backportPP'; }
521 use JSON;
522
523 =head1 USING OPTIONAL FEATURES
524
525 There are a few options you can set when you C<use> this module.
526 These historical options are only kept for backward compatibility,
527 and should not be used in a new application.
528
529 =over
530
531 =item -support_by_pp
532
533 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
534
535 use JSON -support_by_pp;
536
537 my $json = JSON->new;
538 # escape_slash is for JSON::PP only.
539 $json->allow_nonref->escape_slash->encode("/");
540
541 With this option, this module loads its pure perl backend along with
542 its XS backend (if available), and lets the XS backend to watch if you set
543 a flag only JSON::PP supports. When you do, the internal JSON::XS object
544 is replaced with a newly created JSON::PP object with the setting copied
545 from the XS object, so that you can use JSON::PP flags (and its slower
546 C<decode>/C<encode> methods) from then on. In other words, this is not
547 something that allows you to hook JSON::XS to change its behavior while
548 keeping its speed. JSON::XS and JSON::PP objects are quite different
549 (JSON::XS object is a blessed scalar reference, while JSON::PP object is
550 a blessed hash reference), and can't share their internals.
551
552 To avoid needless overhead (by copying settings), you are advised not
553 to use this option and just to use JSON::PP explicitly when you need
554 JSON::PP features.
555
556 =item -convert_blessed_universally
557
558 use JSON -convert_blessed_universally;
559
560 my $json = JSON->new->allow_nonref->convert_blessed;
561 my $object = bless {foo => 'bar'}, 'Foo';
562 $json->encode($object); # => {"foo":"bar"}
563
564 JSON::XS-compatible backend modules don't encode blessed objects by
565 default (except for their boolean values, which are typically blessed
566 JSON::PP::Boolean objects). If you need to encode a data structure
567 that may contain objects, you usually need to look into the structure
568 and replace objects with alternative non-blessed values, or enable
569 C<convert_blessed> and provide a C<TO_JSON> method for each object's
570 (base) class that may be found in the structure, in order to let the
571 methods replace the objects with whatever scalar values the methods
572 return.
573
574 If you need to serialise data structures that may contain arbitrary
575 objects, it's probably better to use other serialisers (such as
576 L<Sereal> or L<Storable> for example), but if you do want to use
577 this module for that purpose, C<-convert_blessed_universally> option
578 may help, which tweaks C<encode> method of the backend to install
579 C<UNIVERSAL::TO_JSON> method (locally) before encoding, so that
580 all the objects that don't have their own C<TO_JSON> method can
581 fall back on the method in the C<UNIVERSAL> namespace. Note that you
582 still need to enable C<convert_blessed> flag to actually encode
583 objects in a data structure, and C<UNIVERSAL::TO_JSON> method
584 installed by this option only converts blessed hash/array references
585 into their unblessed clone (including private keys/values that are
586 not supposed to be exposed). Other blessed references will be
587 converted into null.
588
589 This feature is experimental and may be removed in the future.
590
591 =item -no_export
592
593 When you don't want to import functional interfaces from a module, you
594 usually supply C<()> to its C<use> statement.
595
596 use JSON (); # no functional interfaces
597
598 If you don't want to import functional interfaces, but you also want to
599 use any of the above options, add C<-no_export> to the option list.
600
601 # no functional interfaces, while JSON::PP support is enabled.
602 use JSON -support_by_pp, -no_export;
603
604 =back
605
606 =head1 FUNCTIONAL INTERFACE
607
608 This section is taken from JSON::XS. C<encode_json> and C<decode_json>
609 are exported by default.
610
611 This module also exports C<to_json> and C<from_json> for backward
612 compatibility. These are slower, and may expect/generate different stuff
613 from what C<encode_json> and C<decode_json> do, depending on their
614 options. It's better just to use Object-Oriented interfaces than using
615 these two functions.
616
617 =head2 encode_json
618
619 $json_text = encode_json $perl_scalar
620
621 Converts the given Perl data structure to a UTF-8 encoded, binary string
622 (that is, the string contains octets only). Croaks on error.
623
624 This function call is functionally identical to:
625
626 $json_text = JSON->new->utf8->encode($perl_scalar)
627
628 Except being faster.
629
630 =head2 decode_json
631
632 $perl_scalar = decode_json $json_text
633
634 The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
635 to parse that as an UTF-8 encoded JSON text, returning the resulting
636 reference. Croaks on error.
637
638 This function call is functionally identical to:
639
640 $perl_scalar = JSON->new->utf8->decode($json_text)
641
642 Except being faster.
643
644 =head2 to_json
645
646 $json_text = to_json($perl_scalar[, $optional_hashref])
647
648 Converts the given Perl data structure to a Unicode string by default.
649 Croaks on error.
650
651 Basically, this function call is functionally identical to:
652
653 $json_text = JSON->new->encode($perl_scalar)
654
655 Except being slower.
656
657 You can pass an optional hash reference to modify its behavior, but
658 that may change what C<to_json> expects/generates (see
659 C<ENCODING/CODESET FLAG NOTES> for details).
660
661 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
662 # => JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
663
664 =head2 from_json
665
666 $perl_scalar = from_json($json_text[, $optional_hashref])
667
668 The opposite of C<to_json>: expects a Unicode string and tries
669 to parse it, returning the resulting reference. Croaks on error.
670
671 Basically, this function call is functionally identical to:
672
673 $perl_scalar = JSON->new->decode($json_text)
674
675 You can pass an optional hash reference to modify its behavior, but
676 that may change what C<from_json> expects/generates (see
677 C<ENCODING/CODESET FLAG NOTES> for details).
678
679 $perl_scalar = from_json($json_text, {utf8 => 1})
680 # => JSON->new->utf8(1)->decode($json_text)
681
682 =head2 JSON::is_bool
683
684 $is_boolean = JSON::is_bool($scalar)
685
686 Returns true if the passed scalar represents either JSON::true or
687 JSON::false, two constants that act like C<1> and C<0> respectively
688 and are also used to represent JSON C<true> and C<false> in Perl strings.
689
690 See L<MAPPING>, below, for more information on how JSON values are mapped to
691 Perl.
692
693 =head1 COMMON OBJECT-ORIENTED INTERFACE
694
695 This section is also taken from JSON::XS.
696
697 The object oriented interface lets you configure your own encoding or
698 decoding style, within the limits of supported formats.
699
700 =head2 new
701
702 $json = JSON->new
703
704 Creates a new JSON::XS-compatible backend object that can be used to de/encode JSON
705 strings. All boolean flags described below are by default I<disabled>
706 (with the exception of C<allow_nonref>, which defaults to I<enabled> since
707 version C<4.0>).
708
709 The mutators for flags all return the backend object again and thus calls can
710 be chained:
711
712 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
713 => {"a": [1, 2]}
714
715 =head2 ascii
716
717 $json = $json->ascii([$enable])
718
719 $enabled = $json->get_ascii
720
721 If C<$enable> is true (or missing), then the C<encode> method will not
722 generate characters outside the code range C<0..127> (which is ASCII). Any
723 Unicode characters outside that range will be escaped using either a
724 single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence,
725 as per RFC4627. The resulting encoded JSON text can be treated as a native
726 Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string,
727 or any other superset of ASCII.
728
729 If C<$enable> is false, then the C<encode> method will not escape Unicode
730 characters unless required by the JSON syntax or other flags. This results
731 in a faster and more compact format.
732
733 See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
734
735 The main use for this flag is to produce JSON texts that can be
736 transmitted over a 7-bit channel, as the encoded JSON texts will not
737 contain any 8 bit characters.
738
739 JSON->new->ascii(1)->encode([chr 0x10401])
740 => ["\ud801\udc01"]
741
742 =head2 latin1
743
744 $json = $json->latin1([$enable])
745
746 $enabled = $json->get_latin1
747
748 If C<$enable> is true (or missing), then the C<encode> method will encode
749 the resulting JSON text as latin1 (or iso-8859-1), escaping any characters
750 outside the code range C<0..255>. The resulting string can be treated as a
751 latin1-encoded JSON text or a native Unicode string. The C<decode> method
752 will not be affected in any way by this flag, as C<decode> by default
753 expects Unicode, which is a strict superset of latin1.
754
755 If C<$enable> is false, then the C<encode> method will not escape Unicode
756 characters unless required by the JSON syntax or other flags.
757
758 See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
759
760 The main use for this flag is efficiently encoding binary data as JSON
761 text, as most octets will not be escaped, resulting in a smaller encoded
762 size. The disadvantage is that the resulting JSON text is encoded
763 in latin1 (and must correctly be treated as such when storing and
764 transferring), a rare encoding for JSON. It is therefore most useful when
765 you want to store data structures known to contain binary data efficiently
766 in files or databases, not when talking to other JSON encoders/decoders.
767
768 JSON->new->latin1->encode (["\x{89}\x{abc}"]
769 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
770
771 =head2 utf8
772
773 $json = $json->utf8([$enable])
774
775 $enabled = $json->get_utf8
776
777 If C<$enable> is true (or missing), then the C<encode> method will encode
778 the JSON result into UTF-8, as required by many protocols, while the
779 C<decode> method expects to be handled an UTF-8-encoded string. Please
780 note that UTF-8-encoded strings do not contain any characters outside the
781 range C<0..255>, they are thus useful for bytewise/binary I/O. In future
782 versions, enabling this option might enable autodetection of the UTF-16
783 and UTF-32 encoding families, as described in RFC4627.
784
785 If C<$enable> is false, then the C<encode> method will return the JSON
786 string as a (non-encoded) Unicode string, while C<decode> expects thus a
787 Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
788 to be done yourself, e.g. using the Encode module.
789
790 See also the section I<ENCODING/CODESET FLAG NOTES> later in this document.
791
792 Example, output UTF-16BE-encoded JSON:
793
794 use Encode;
795 $jsontext = encode "UTF-16BE", JSON->new->encode ($object);
796
797 Example, decode UTF-32LE-encoded JSON:
798
799 use Encode;
800 $object = JSON->new->decode (decode "UTF-32LE", $jsontext);
801
802 =head2 pretty
803
804 $json = $json->pretty([$enable])
805
806 This enables (or disables) all of the C<indent>, C<space_before> and
807 C<space_after> (and in the future possibly more) flags in one call to
808 generate the most readable (or most compact) form possible.
809
810 =head2 indent
811
812 $json = $json->indent([$enable])
813
814 $enabled = $json->get_indent
815
816 If C<$enable> is true (or missing), then the C<encode> method will use a multiline
817 format as output, putting every array member or object/hash key-value pair
818 into its own line, indenting them properly.
819
820 If C<$enable> is false, no newlines or indenting will be produced, and the
821 resulting JSON text is guaranteed not to contain any C<newlines>.
822
823 This setting has no effect when decoding JSON texts.
824
825 =head2 space_before
826
827 $json = $json->space_before([$enable])
828
829 $enabled = $json->get_space_before
830
831 If C<$enable> is true (or missing), then the C<encode> method will add an extra
832 optional space before the C<:> separating keys from values in JSON objects.
833
834 If C<$enable> is false, then the C<encode> method will not add any extra
835 space at those places.
836
837 This setting has no effect when decoding JSON texts. You will also
838 most likely combine this setting with C<space_after>.
839
840 Example, space_before enabled, space_after and indent disabled:
841
842 {"key" :"value"}
843
844 =head2 space_after
845
846 $json = $json->space_after([$enable])
847
848 $enabled = $json->get_space_after
849
850 If C<$enable> is true (or missing), then the C<encode> method will add an extra
851 optional space after the C<:> separating keys from values in JSON objects
852 and extra whitespace after the C<,> separating key-value pairs and array
853 members.
854
855 If C<$enable> is false, then the C<encode> method will not add any extra
856 space at those places.
857
858 This setting has no effect when decoding JSON texts.
859
860 Example, space_before and indent disabled, space_after enabled:
861
862 {"key": "value"}
863
864 =head2 relaxed
865
866 $json = $json->relaxed([$enable])
867
868 $enabled = $json->get_relaxed
869
870 If C<$enable> is true (or missing), then C<decode> will accept some
871 extensions to normal JSON syntax (see below). C<encode> will not be
872 affected in any way. I<Be aware that this option makes you accept invalid
873 JSON texts as if they were valid!>. I suggest only to use this option to
874 parse application-specific files written by humans (configuration files,
875 resource files etc.)
876
877 If C<$enable> is false (the default), then C<decode> will only accept
878 valid JSON texts.
879
880 Currently accepted extensions are:
881
882 =over 4
883
884 =item * list items can have an end-comma
885
886 JSON I<separates> array elements and key-value pairs with commas. This
887 can be annoying if you write JSON texts manually and want to be able to
888 quickly append elements, so this extension accepts comma at the end of
889 such items not just between them:
890
891 [
892 1,
893 2, <- this comma not normally allowed
894 ]
895 {
896 "k1": "v1",
897 "k2": "v2", <- this comma not normally allowed
898 }
899
900 =item * shell-style '#'-comments
901
902 Whenever JSON allows whitespace, shell-style comments are additionally
903 allowed. They are terminated by the first carriage-return or line-feed
904 character, after which more white-space and comments are allowed.
905
906 [
907 1, # this comment not allowed in JSON
908 # neither this one...
909 ]
910
911 =back
912
913 =head2 canonical
914
915 $json = $json->canonical([$enable])
916
917 $enabled = $json->get_canonical
918
919 If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
920 by sorting their keys. This is adding a comparatively high overhead.
921
922 If C<$enable> is false, then the C<encode> method will output key-value
923 pairs in the order Perl stores them (which will likely change between runs
924 of the same script, and can change even within the same run from 5.18
925 onwards).
926
927 This option is useful if you want the same data structure to be encoded as
928 the same JSON text (given the same overall settings). If it is disabled,
929 the same hash might be encoded differently even if contains the same data,
930 as key-value pairs have no inherent ordering in Perl.
931
932 This setting has no effect when decoding JSON texts.
933
934 This setting has currently no effect on tied hashes.
935
936 =head2 allow_nonref
937
938 $json = $json->allow_nonref([$enable])
939
940 $enabled = $json->get_allow_nonref
941
942 Unlike other boolean options, this option is enabled by default beginning
943 with version C<4.0>.
944
945 If C<$enable> is true (or missing), then the C<encode> method can convert a
946 non-reference into its corresponding string, number or null JSON value,
947 which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
948 values instead of croaking.
949
950 If C<$enable> is false, then the C<encode> method will croak if it isn't
951 passed an arrayref or hashref, as JSON texts must either be an object
952 or array. Likewise, C<decode> will croak if given something that is not a
953 JSON object or array.
954
955 Example, encode a Perl scalar as JSON value with enabled C<allow_nonref>,
956 resulting in an invalid JSON text:
957
958 JSON->new->allow_nonref->encode ("Hello, World!")
959 => "Hello, World!"
960
961 =head2 allow_unknown
962
963 $json = $json->allow_unknown ([$enable])
964
965 $enabled = $json->get_allow_unknown
966
967 If C<$enable> is true (or missing), then C<encode> will I<not> throw an
968 exception when it encounters values it cannot represent in JSON (for
969 example, filehandles) but instead will encode a JSON C<null> value. Note
970 that blessed objects are not included here and are handled separately by
971 c<allow_blessed>.
972
973 If C<$enable> is false (the default), then C<encode> will throw an
974 exception when it encounters anything it cannot encode as JSON.
975
976 This option does not affect C<decode> in any way, and it is recommended to
977 leave it off unless you know your communications partner.
978
979 =head2 allow_blessed
980
981 $json = $json->allow_blessed([$enable])
982
983 $enabled = $json->get_allow_blessed
984
985 See L<OBJECT SERIALISATION> for details.
986
987 If C<$enable> is true (or missing), then the C<encode> method will not
988 barf when it encounters a blessed reference that it cannot convert
989 otherwise. Instead, a JSON C<null> value is encoded instead of the object.
990
991 If C<$enable> is false (the default), then C<encode> will throw an
992 exception when it encounters a blessed object that it cannot convert
993 otherwise.
994
995 This setting has no effect on C<decode>.
996
997 =head2 convert_blessed
998
999 $json = $json->convert_blessed([$enable])
1000
1001 $enabled = $json->get_convert_blessed
1002
1003 See L<OBJECT SERIALISATION> for details.
1004
1005 If C<$enable> is true (or missing), then C<encode>, upon encountering a
1006 blessed object, will check for the availability of the C<TO_JSON> method
1007 on the object's class. If found, it will be called in scalar context and
1008 the resulting scalar will be encoded instead of the object.
1009
1010 The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
1011 returns other blessed objects, those will be handled in the same
1012 way. C<TO_JSON> must take care of not causing an endless recursion cycle
1013 (== crash) in this case. The name of C<TO_JSON> was chosen because other
1014 methods called by the Perl core (== not by the user of the object) are
1015 usually in upper case letters and to avoid collisions with any C<to_json>
1016 function or method.
1017
1018 If C<$enable> is false (the default), then C<encode> will not consider
1019 this type of conversion.
1020
1021 This setting has no effect on C<decode>.
1022
1023 =head2 allow_tags (since version 3.0)
1024
1025 $json = $json->allow_tags([$enable])
1026
1027 $enabled = $json->get_allow_tags
1028
1029 See L<OBJECT SERIALISATION> for details.
1030
1031 If C<$enable> is true (or missing), then C<encode>, upon encountering a
1032 blessed object, will check for the availability of the C<FREEZE> method on
1033 the object's class. If found, it will be used to serialise the object into
1034 a nonstandard tagged JSON value (that JSON decoders cannot decode).
1035
1036 It also causes C<decode> to parse such tagged JSON values and deserialise
1037 them via a call to the C<THAW> method.
1038
1039 If C<$enable> is false (the default), then C<encode> will not consider
1040 this type of conversion, and tagged JSON values will cause a parse error
1041 in C<decode>, as if tags were not part of the grammar.
1042
1043 =head2 boolean_values (since version 4.0)
1044
1045 $json->boolean_values([$false, $true])
1046
1047 ($false, $true) = $json->get_boolean_values
1048
1049 By default, JSON booleans will be decoded as overloaded
1050 C<$JSON::false> and C<$JSON::true> objects.
1051
1052 With this method you can specify your own boolean values for decoding -
1053 on decode, JSON C<false> will be decoded as a copy of C<$false>, and JSON
1054 C<true> will be decoded as C<$true> ("copy" here is the same thing as
1055 assigning a value to another variable, i.e. C<$copy = $false>).
1056
1057 This is useful when you want to pass a decoded data structure directly
1058 to other serialisers like YAML, Data::MessagePack and so on.
1059
1060 Note that this works only when you C<decode>. You can set incompatible
1061 boolean objects (like L<boolean>), but when you C<encode> a data structure
1062 with such boolean objects, you still need to enable C<convert_blessed>
1063 (and add a C<TO_JSON> method if necessary).
1064
1065 Calling this method without any arguments will reset the booleans
1066 to their default values.
1067
1068 C<get_boolean_values> will return both C<$false> and C<$true> values, or
1069 the empty list when they are set to the default.
1070
1071 =head2 filter_json_object
1072
1073 $json = $json->filter_json_object([$coderef])
1074
1075 When C<$coderef> is specified, it will be called from C<decode> each
1076 time it decodes a JSON object. The only argument is a reference to
1077 the newly-created hash. If the code references returns a single scalar
1078 (which need not be a reference), this value (or rather a copy of it) is
1079 inserted into the deserialised data structure. If it returns an empty
1080 list (NOTE: I<not> C<undef>, which is a valid scalar), the original
1081 deserialised hash will be inserted. This setting can slow down decoding
1082 considerably.
1083
1084 When C<$coderef> is omitted or undefined, any existing callback will
1085 be removed and C<decode> will not change the deserialised hash in any
1086 way.
1087
1088 Example, convert all JSON objects into the integer 5:
1089
1090 my $js = JSON->new->filter_json_object(sub { 5 });
1091 # returns [5]
1092 $js->decode('[{}]');
1093 # returns 5
1094 $js->decode('{"a":1, "b":2}');
1095
1096 =head2 filter_json_single_key_object
1097
1098 $json = $json->filter_json_single_key_object($key [=> $coderef])
1099
1100 Works remotely similar to C<filter_json_object>, but is only called for
1101 JSON objects having a single key named C<$key>.
1102
1103 This C<$coderef> is called before the one specified via
1104 C<filter_json_object>, if any. It gets passed the single value in the JSON
1105 object. If it returns a single value, it will be inserted into the data
1106 structure. If it returns nothing (not even C<undef> but the empty list),
1107 the callback from C<filter_json_object> will be called next, as if no
1108 single-key callback were specified.
1109
1110 If C<$coderef> is omitted or undefined, the corresponding callback will be
1111 disabled. There can only ever be one callback for a given key.
1112
1113 As this callback gets called less often then the C<filter_json_object>
1114 one, decoding speed will not usually suffer as much. Therefore, single-key
1115 objects make excellent targets to serialise Perl objects into, especially
1116 as single-key JSON objects are as close to the type-tagged value concept
1117 as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
1118 support this in any way, so you need to make sure your data never looks
1119 like a serialised Perl hash.
1120
1121 Typical names for the single object key are C<__class_whatever__>, or
1122 C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
1123 things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
1124 with real hashes.
1125
1126 Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
1127 into the corresponding C<< $WIDGET{<id>} >> object:
1128
1129 # return whatever is in $WIDGET{5}:
1130 JSON
1131 ->new
1132 ->filter_json_single_key_object (__widget__ => sub {
1133 $WIDGET{ $_[0] }
1134 })
1135 ->decode ('{"__widget__": 5')
1136
1137 # this can be used with a TO_JSON method in some "widget" class
1138 # for serialisation to json:
1139 sub WidgetBase::TO_JSON {
1140 my ($self) = @_;
1141
1142 unless ($self->{id}) {
1143 $self->{id} = ..get..some..id..;
1144 $WIDGET{$self->{id}} = $self;
1145 }
1146
1147 { __widget__ => $self->{id} }
1148 }
1149
1150 =head2 max_depth
1151
1152 $json = $json->max_depth([$maximum_nesting_depth])
1153
1154 $max_depth = $json->get_max_depth
1155
1156 Sets the maximum nesting level (default C<512>) accepted while encoding
1157 or decoding. If a higher nesting level is detected in JSON text or a Perl
1158 data structure, then the encoder and decoder will stop and croak at that
1159 point.
1160
1161 Nesting level is defined by number of hash- or arrayrefs that the encoder
1162 needs to traverse to reach a given point or the number of C<{> or C<[>
1163 characters without their matching closing parenthesis crossed to reach a
1164 given character in a string.
1165
1166 Setting the maximum depth to one disallows any nesting, so that ensures
1167 that the object is only a single hash/object or array.
1168
1169 If no argument is given, the highest possible setting will be used, which
1170 is rarely useful.
1171
1172 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1173
1174 =head2 max_size
1175
1176 $json = $json->max_size([$maximum_string_size])
1177
1178 $max_size = $json->get_max_size
1179
1180 Set the maximum length a JSON text may have (in bytes) where decoding is
1181 being attempted. The default is C<0>, meaning no limit. When C<decode>
1182 is called on a string that is longer then this many bytes, it will not
1183 attempt to decode the string but throw an exception. This setting has no
1184 effect on C<encode> (yet).
1185
1186 If no argument is given, the limit check will be deactivated (same as when
1187 C<0> is specified).
1188
1189 See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1190
1191 =head2 encode
1192
1193 $json_text = $json->encode($perl_scalar)
1194
1195 Converts the given Perl value or data structure to its JSON
1196 representation. Croaks on error.
1197
1198 =head2 decode
1199
1200 $perl_scalar = $json->decode($json_text)
1201
1202 The opposite of C<encode>: expects a JSON text and tries to parse it,
1203 returning the resulting simple scalar or reference. Croaks on error.
1204
1205 =head2 decode_prefix
1206
1207 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
1208
1209 This works like the C<decode> method, but instead of raising an exception
1210 when there is trailing garbage after the first JSON object, it will
1211 silently stop parsing there and return the number of characters consumed
1212 so far.
1213
1214 This is useful if your JSON texts are not delimited by an outer protocol
1215 and you need to know where the JSON text ends.
1216
1217 JSON->new->decode_prefix ("[1] the tail")
1218 => ([1], 3)
1219
1220 =head1 ADDITIONAL METHODS
1221
1222 The following methods are for this module only.
1223
1224 =head2 backend
1225
1226 $backend = $json->backend
1227
1228 Since 2.92, C<backend> method returns an abstract backend module used currently,
1229 which should be JSON::Backend::XS (which inherits JSON::XS or Cpanel::JSON::XS),
1230 or JSON::Backend::PP (which inherits JSON::PP), not to monkey-patch the actual
1231 backend module globally.
1232
1233 If you need to know what is used actually, use C<isa>, instead of string comparison.
1234
1235 =head2 is_xs
1236
1237 $boolean = $json->is_xs
1238
1239 Returns true if the backend inherits JSON::XS or Cpanel::JSON::XS.
1240
1241 =head2 is_pp
1242
1243 $boolean = $json->is_pp
1244
1245 Returns true if the backend inherits JSON::PP.
1246
1247 =head2 property
1248
1249 $settings = $json->property()
1250
1251 Returns a reference to a hash that holds all the common flag settings.
1252
1253 $json = $json->property('utf8' => 1)
1254 $value = $json->property('utf8') # 1
1255
1256 You can use this to get/set a value of a particular flag.
1257
1258 =head2 boolean
1259
1260 $boolean_object = JSON->boolean($scalar)
1261
1262 Returns $JSON::true if $scalar contains a true value, $JSON::false otherwise.
1263 You can use this as a full-qualified function (C<JSON::boolean($scalar)>).
1264
1265 =head1 INCREMENTAL PARSING
1266
1267 This section is also taken from JSON::XS.
1268
1269 In some cases, there is the need for incremental parsing of JSON
1270 texts. While this module always has to keep both JSON text and resulting
1271 Perl data structure in memory at one time, it does allow you to parse a
1272 JSON stream incrementally. It does so by accumulating text until it has
1273 a full JSON object, which it then can decode. This process is similar to
1274 using C<decode_prefix> to see if a full JSON object is available, but
1275 is much more efficient (and can be implemented with a minimum of method
1276 calls).
1277
1278 This module will only attempt to parse the JSON text once it is sure it
1279 has enough text to get a decisive result, using a very simple but
1280 truly incremental parser. This means that it sometimes won't stop as
1281 early as the full parser, for example, it doesn't detect mismatched
1282 parentheses. The only thing it guarantees is that it starts decoding as
1283 soon as a syntactically valid JSON text has been seen. This means you need
1284 to set resource limits (e.g. C<max_size>) to ensure the parser will stop
1285 parsing in the presence if syntax errors.
1286
1287 The following methods implement this incremental parser.
1288
1289 =head2 incr_parse
1290
1291 $json->incr_parse( [$string] ) # void context
1292
1293 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
1294
1295 @obj_or_empty = $json->incr_parse( [$string] ) # list context
1296
1297 This is the central parsing function. It can both append new text and
1298 extract objects from the stream accumulated so far (both of these
1299 functions are optional).
1300
1301 If C<$string> is given, then this string is appended to the already
1302 existing JSON fragment stored in the C<$json> object.
1303
1304 After that, if the function is called in void context, it will simply
1305 return without doing anything further. This can be used to add more text
1306 in as many chunks as you want.
1307
1308 If the method is called in scalar context, then it will try to extract
1309 exactly I<one> JSON object. If that is successful, it will return this
1310 object, otherwise it will return C<undef>. If there is a parse error,
1311 this method will croak just as C<decode> would do (one can then use
1312 C<incr_skip> to skip the erroneous part). This is the most common way of
1313 using the method.
1314
1315 And finally, in list context, it will try to extract as many objects
1316 from the stream as it can find and return them, or the empty list
1317 otherwise. For this to work, there must be no separators (other than
1318 whitespace) between the JSON objects or arrays, instead they must be
1319 concatenated back-to-back. If an error occurs, an exception will be
1320 raised as in the scalar context case. Note that in this case, any
1321 previously-parsed JSON texts will be lost.
1322
1323 Example: Parse some JSON arrays/objects in a given string and return
1324 them.
1325
1326 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
1327
1328 =head2 incr_text
1329
1330 $lvalue_string = $json->incr_text
1331
1332 This method returns the currently stored JSON fragment as an lvalue, that
1333 is, you can manipulate it. This I<only> works when a preceding call to
1334 C<incr_parse> in I<scalar context> successfully returned an object. Under
1335 all other circumstances you must not call this function (I mean it.
1336 although in simple tests it might actually work, it I<will> fail under
1337 real world conditions). As a special exception, you can also call this
1338 method before having parsed anything.
1339
1340 That means you can only use this function to look at or manipulate text
1341 before or after complete JSON objects, not while the parser is in the
1342 middle of parsing a JSON object.
1343
1344 This function is useful in two cases: a) finding the trailing text after a
1345 JSON object or b) parsing multiple JSON objects separated by non-JSON text
1346 (such as commas).
1347
1348 =head2 incr_skip
1349
1350 $json->incr_skip
1351
1352 This will reset the state of the incremental parser and will remove
1353 the parsed text from the input buffer so far. This is useful after
1354 C<incr_parse> died, in which case the input buffer and incremental parser
1355 state is left unchanged, to skip the text parsed so far and to reset the
1356 parse state.
1357
1358 The difference to C<incr_reset> is that only text until the parse error
1359 occurred is removed.
1360
1361 =head2 incr_reset
1362
1363 $json->incr_reset
1364
1365 This completely resets the incremental parser, that is, after this call,
1366 it will be as if the parser had never parsed anything.
1367
1368 This is useful if you want to repeatedly parse JSON objects and want to
1369 ignore any trailing data, which means you have to reset the parser after
1370 each successful decode.
1371
1372 =head1 MAPPING
1373
1374 Most of this section is also taken from JSON::XS.
1375
1376 This section describes how the backend modules map Perl values to JSON values and
1377 vice versa. These mappings are designed to "do the right thing" in most
1378 circumstances automatically, preserving round-tripping characteristics
1379 (what you put in comes out as something equivalent).
1380
1381 For the more enlightened: note that in the following descriptions,
1382 lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl>
1383 refers to the abstract Perl language itself.
1384
1385 =head2 JSON -> PERL
1386
1387 =over 4
1388
1389 =item object
1390
1391 A JSON object becomes a reference to a hash in Perl. No ordering of object
1392 keys is preserved (JSON does not preserver object key ordering itself).
1393
1394 =item array
1395
1396 A JSON array becomes a reference to an array in Perl.
1397
1398 =item string
1399
1400 A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1401 are represented by the same codepoints in the Perl string, so no manual
1402 decoding is necessary.
1403
1404 =item number
1405
1406 A JSON number becomes either an integer, numeric (floating point) or
1407 string scalar in perl, depending on its range and any fractional parts. On
1408 the Perl level, there is no difference between those as Perl handles all
1409 the conversion details, but an integer may take slightly less memory and
1410 might represent more values exactly than floating point numbers.
1411
1412 If the number consists of digits only, this module will try to represent
1413 it as an integer value. If that fails, it will try to represent it as
1414 a numeric (floating point) value if that is possible without loss of
1415 precision. Otherwise it will preserve the number as a string value (in
1416 which case you lose roundtripping ability, as the JSON number will be
1417 re-encoded to a JSON string).
1418
1419 Numbers containing a fractional or exponential part will always be
1420 represented as numeric (floating point) values, possibly at a loss of
1421 precision (in which case you might lose perfect roundtripping ability, but
1422 the JSON number will still be re-encoded as a JSON number).
1423
1424 Note that precision is not accuracy - binary floating point values cannot
1425 represent most decimal fractions exactly, and when converting from and to
1426 floating point, this module only guarantees precision up to but not including
1427 the least significant bit.
1428
1429 =item true, false
1430
1431 These JSON atoms become C<JSON::true> and C<JSON::false>,
1432 respectively. They are overloaded to act almost exactly like the numbers
1433 C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
1434 the C<JSON::is_bool> function.
1435
1436 =item null
1437
1438 A JSON null atom becomes C<undef> in Perl.
1439
1440 =item shell-style comments (C<< # I<text> >>)
1441
1442 As a nonstandard extension to the JSON syntax that is enabled by the
1443 C<relaxed> setting, shell-style comments are allowed. They can start
1444 anywhere outside strings and go till the end of the line.
1445
1446 =item tagged values (C<< (I<tag>)I<value> >>).
1447
1448 Another nonstandard extension to the JSON syntax, enabled with the
1449 C<allow_tags> setting, are tagged values. In this implementation, the
1450 I<tag> must be a perl package/class name encoded as a JSON string, and the
1451 I<value> must be a JSON array encoding optional constructor arguments.
1452
1453 See L<OBJECT SERIALISATION>, below, for details.
1454
1455 =back
1456
1457
1458 =head2 PERL -> JSON
1459
1460 The mapping from Perl to JSON is slightly more difficult, as Perl is a
1461 truly typeless language, so we can only guess which JSON type is meant by
1462 a Perl value.
1463
1464 =over 4
1465
1466 =item hash references
1467
1468 Perl hash references become JSON objects. As there is no inherent
1469 ordering in hash keys (or JSON objects), they will usually be encoded
1470 in a pseudo-random order. This module can optionally sort the hash keys
1471 (determined by the I<canonical> flag), so the same data structure will
1472 serialise to the same JSON text (given same settings and version of
1473 the same backend), but this incurs a runtime overhead and is only rarely useful,
1474 e.g. when you want to compare some JSON text against another for equality.
1475
1476 =item array references
1477
1478 Perl array references become JSON arrays.
1479
1480 =item other references
1481
1482 Other unblessed references are generally not allowed and will cause an
1483 exception to be thrown, except for references to the integers C<0> and
1484 C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1485 also use C<JSON::false> and C<JSON::true> to improve readability.
1486
1487 encode_json [\0,JSON::true] # yields [false,true]
1488
1489 =item JSON::true, JSON::false, JSON::null
1490
1491 These special values become JSON true and JSON false values,
1492 respectively. You can also use C<\1> and C<\0> directly if you want.
1493
1494 =item blessed objects
1495
1496 Blessed objects are not directly representable in JSON, but C<JSON::XS>
1497 allows various ways of handling objects. See L<OBJECT SERIALISATION>,
1498 below, for details.
1499
1500 =item simple scalars
1501
1502 Simple Perl scalars (any scalar that is not a reference) are the most
1503 difficult objects to encode: this module will encode undefined scalars as
1504 JSON C<null> values, scalars that have last been used in a string context
1505 before encoding as JSON strings, and anything else as number value:
1506
1507 # dump as number
1508 encode_json [2] # yields [2]
1509 encode_json [-3.0e17] # yields [-3e+17]
1510 my $value = 5; encode_json [$value] # yields [5]
1511
1512 # used as string, so dump as string
1513 print $value;
1514 encode_json [$value] # yields ["5"]
1515
1516 # undef becomes null
1517 encode_json [undef] # yields [null]
1518
1519 You can force the type to be a string by stringifying it:
1520
1521 my $x = 3.1; # some variable containing a number
1522 "$x"; # stringified
1523 $x .= ""; # another, more awkward way to stringify
1524 print $x; # perl does it for you, too, quite often
1525
1526 You can force the type to be a number by numifying it:
1527
1528 my $x = "3"; # some variable containing a string
1529 $x += 0; # numify it, ensuring it will be dumped as a number
1530 $x *= 1; # same thing, the choice is yours.
1531
1532 You can not currently force the type in other, less obscure, ways. Tell me
1533 if you need this capability (but don't forget to explain why it's needed
1534 :).
1535
1536 Since version 2.91_01, JSON::PP uses a different number detection logic
1537 that converts a scalar that is possible to turn into a number safely.
1538 The new logic is slightly faster, and tends to help people who use older
1539 perl or who want to encode complicated data structure. However, this may
1540 results in a different JSON text from the one JSON::XS encodes (and
1541 thus may break tests that compare entire JSON texts). If you do
1542 need the previous behavior for better compatibility or for finer control,
1543 set PERL_JSON_PP_USE_B environmental variable to true before you
1544 C<use> JSON.
1545
1546 Note that numerical precision has the same meaning as under Perl (so
1547 binary to decimal conversion follows the same rules as in Perl, which
1548 can differ to other languages). Also, your perl interpreter might expose
1549 extensions to the floating point numbers of your platform, such as
1550 infinities or NaN's - these cannot be represented in JSON, and it is an
1551 error to pass those in.
1552
1553 JSON.pm backend modules trust what you pass to C<encode> method
1554 (or C<encode_json> function) is a clean, validated data structure with
1555 values that can be represented as valid JSON values only, because it's
1556 not from an external data source (as opposed to JSON texts you pass to
1557 C<decode> or C<decode_json>, which JSON backends consider tainted and
1558 don't trust). As JSON backends don't know exactly what you and consumers
1559 of your JSON texts want the unexpected values to be (you may want to
1560 convert them into null, or to stringify them with or without
1561 normalisation (string representation of infinities/NaN may vary
1562 depending on platforms), or to croak without conversion), you're advised
1563 to do what you and your consumers need before you encode, and also not
1564 to numify values that may start with values that look like a number
1565 (including infinities/NaN), without validating.
1566
1567 =back
1568
1569 =head2 OBJECT SERIALISATION
1570
1571 As JSON cannot directly represent Perl objects, you have to choose between
1572 a pure JSON representation (without the ability to deserialise the object
1573 automatically again), and a nonstandard extension to the JSON syntax,
1574 tagged values.
1575
1576 =head3 SERIALISATION
1577
1578 What happens when this module encounters a Perl object depends on the
1579 C<allow_blessed>, C<convert_blessed> and C<allow_tags> settings, which
1580 are used in this order:
1581
1582 =over 4
1583
1584 =item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method.
1585
1586 In this case, C<JSON> creates a tagged JSON value, using a nonstandard
1587 extension to the JSON syntax.
1588
1589 This works by invoking the C<FREEZE> method on the object, with the first
1590 argument being the object to serialise, and the second argument being the
1591 constant string C<JSON> to distinguish it from other serialisers.
1592
1593 The C<FREEZE> method can return any number of values (i.e. zero or
1594 more). These values and the package/classname of the object will then be
1595 encoded as a tagged JSON value in the following format:
1596
1597 ("classname")[FREEZE return values...]
1598
1599 e.g.:
1600
1601 ("URI")["http://www.google.com/"]
1602 ("MyDate")[2013,10,29]
1603 ("ImageData::JPEG")["Z3...VlCg=="]
1604
1605 For example, the hypothetical C<My::Object> C<FREEZE> method might use the
1606 objects C<type> and C<id> members to encode the object:
1607
1608 sub My::Object::FREEZE {
1609 my ($self, $serialiser) = @_;
1610
1611 ($self->{type}, $self->{id})
1612 }
1613
1614 =item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method.
1615
1616 In this case, the C<TO_JSON> method of the object is invoked in scalar
1617 context. It must return a single scalar that can be directly encoded into
1618 JSON. This scalar replaces the object in the JSON text.
1619
1620 For example, the following C<TO_JSON> method will convert all L<URI>
1621 objects to JSON strings when serialised. The fact that these values
1622 originally were L<URI> objects is lost.
1623
1624 sub URI::TO_JSON {
1625 my ($uri) = @_;
1626 $uri->as_string
1627 }
1628
1629 =item 3. C<allow_blessed> is enabled.
1630
1631 The object will be serialised as a JSON null value.
1632
1633 =item 4. none of the above
1634
1635 If none of the settings are enabled or the respective methods are missing,
1636 this module throws an exception.
1637
1638 =back
1639
1640 =head3 DESERIALISATION
1641
1642 For deserialisation there are only two cases to consider: either
1643 nonstandard tagging was used, in which case C<allow_tags> decides,
1644 or objects cannot be automatically be deserialised, in which
1645 case you can use postprocessing or the C<filter_json_object> or
1646 C<filter_json_single_key_object> callbacks to get some real objects our of
1647 your JSON.
1648
1649 This section only considers the tagged value case: a tagged JSON object
1650 is encountered during decoding and C<allow_tags> is disabled, a parse
1651 error will result (as if tagged values were not part of the grammar).
1652
1653 If C<allow_tags> is enabled, this module will look up the C<THAW> method
1654 of the package/classname used during serialisation (it will not attempt
1655 to load the package as a Perl module). If there is no such method, the
1656 decoding will fail with an error.
1657
1658 Otherwise, the C<THAW> method is invoked with the classname as first
1659 argument, the constant string C<JSON> as second argument, and all the
1660 values from the JSON array (the values originally returned by the
1661 C<FREEZE> method) as remaining arguments.
1662
1663 The method must then return the object. While technically you can return
1664 any Perl scalar, you might have to enable the C<allow_nonref> setting to
1665 make that work in all cases, so better return an actual blessed reference.
1666
1667 As an example, let's implement a C<THAW> function that regenerates the
1668 C<My::Object> from the C<FREEZE> example earlier:
1669
1670 sub My::Object::THAW {
1671 my ($class, $serialiser, $type, $id) = @_;
1672
1673 $class->new (type => $type, id => $id)
1674 }
1675
1676
1677 =head1 ENCODING/CODESET FLAG NOTES
1678
1679 This section is taken from JSON::XS.
1680
1681 The interested reader might have seen a number of flags that signify
1682 encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be
1683 some confusion on what these do, so here is a short comparison:
1684
1685 C<utf8> controls whether the JSON text created by C<encode> (and expected
1686 by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only
1687 control whether C<encode> escapes character values outside their respective
1688 codeset range. Neither of these flags conflict with each other, although
1689 some combinations make less sense than others.
1690
1691 Care has been taken to make all flags symmetrical with respect to
1692 C<encode> and C<decode>, that is, texts encoded with any combination of
1693 these flag values will be correctly decoded when the same flags are used
1694 - in general, if you use different flag settings while encoding vs. when
1695 decoding you likely have a bug somewhere.
1696
1697 Below comes a verbose discussion of these flags. Note that a "codeset" is
1698 simply an abstract set of character-codepoint pairs, while an encoding
1699 takes those codepoint numbers and I<encodes> them, in our case into
1700 octets. Unicode is (among other things) a codeset, UTF-8 is an encoding,
1701 and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at
1702 the same time, which can be confusing.
1703
1704 =over 4
1705
1706 =item C<utf8> flag disabled
1707
1708 When C<utf8> is disabled (the default), then C<encode>/C<decode> generate
1709 and expect Unicode strings, that is, characters with high ordinal Unicode
1710 values (> 255) will be encoded as such characters, and likewise such
1711 characters are decoded as-is, no changes to them will be done, except
1712 "(re-)interpreting" them as Unicode codepoints or Unicode characters,
1713 respectively (to Perl, these are the same thing in strings unless you do
1714 funny/weird/dumb stuff).
1715
1716 This is useful when you want to do the encoding yourself (e.g. when you
1717 want to have UTF-16 encoded JSON texts) or when some other layer does
1718 the encoding for you (for example, when printing to a terminal using a
1719 filehandle that transparently encodes to UTF-8 you certainly do NOT want
1720 to UTF-8 encode your data first and have Perl encode it another time).
1721
1722 =item C<utf8> flag enabled
1723
1724 If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all
1725 characters using the corresponding UTF-8 multi-byte sequence, and will
1726 expect your input strings to be encoded as UTF-8, that is, no "character"
1727 of the input string must have any value > 255, as UTF-8 does not allow
1728 that.
1729
1730 The C<utf8> flag therefore switches between two modes: disabled means you
1731 will get a Unicode string in Perl, enabled means you get an UTF-8 encoded
1732 octet/binary string in Perl.
1733
1734 =item C<latin1> or C<ascii> flags enabled
1735
1736 With C<latin1> (or C<ascii>) enabled, C<encode> will escape characters
1737 with ordinal values > 255 (> 127 with C<ascii>) and encode the remaining
1738 characters as specified by the C<utf8> flag.
1739
1740 If C<utf8> is disabled, then the result is also correctly encoded in those
1741 character sets (as both are proper subsets of Unicode, meaning that a
1742 Unicode string with all character values < 256 is the same thing as a
1743 ISO-8859-1 string, and a Unicode string with all character values < 128 is
1744 the same thing as an ASCII string in Perl).
1745
1746 If C<utf8> is enabled, you still get a correct UTF-8-encoded string,
1747 regardless of these flags, just some more characters will be escaped using
1748 C<\uXXXX> then before.
1749
1750 Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8
1751 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1
1752 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being
1753 a subset of Unicode), while ASCII is.
1754
1755 Surprisingly, C<decode> will ignore these flags and so treat all input
1756 values as governed by the C<utf8> flag. If it is disabled, this allows you
1757 to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of
1758 Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.
1759
1760 So neither C<latin1> nor C<ascii> are incompatible with the C<utf8> flag -
1761 they only govern when the JSON output engine escapes a character or not.
1762
1763 The main use for C<latin1> is to relatively efficiently store binary data
1764 as JSON, at the expense of breaking compatibility with most JSON decoders.
1765
1766 The main use for C<ascii> is to force the output to not contain characters
1767 with values > 127, which means you can interpret the resulting string
1768 as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and
1769 8-bit-encoding, and still get the same data structure back. This is useful
1770 when your channel for JSON transfer is not 8-bit clean or the encoding
1771 might be mangled in between (e.g. in mail), and works because ASCII is a
1772 proper subset of most 8-bit and multibyte encodings in use in the world.
1773
1774 =back
1775
1776 =head1 BACKWARD INCOMPATIBILITY
1777
1778 Since version 2.90, stringification (and string comparison) for
1779 C<JSON::true> and C<JSON::false> has not been overloaded. It shouldn't
1780 matter as long as you treat them as boolean values, but a code that
1781 expects they are stringified as "true" or "false" doesn't work as
1782 you have expected any more.
1783
1784 if (JSON::true eq 'true') { # now fails
1785
1786 print "The result is $JSON::true now."; # => The result is 1 now.
1787
1788 And now these boolean values don't inherit JSON::Boolean, either.
1789 When you need to test a value is a JSON boolean value or not, use
1790 C<JSON::is_bool> function, instead of testing the value inherits
1791 a particular boolean class or not.
1792
1793 =head1 BUGS
1794
1795 Please report bugs on backend selection and additional features
1796 this module provides to RT or GitHub issues for this module:
1797
1798 L<https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON>
1799
1800 L<https://github.com/makamaka/JSON/issues>
1801
1802 As for bugs on a specific behavior, please report to the author
1803 of the backend module you are using.
1804
1805 As for new features and requests to change common behaviors, please
1806 ask the author of JSON::XS (Marc Lehmann, E<lt>schmorp[at]schmorp.deE<gt>)
1807 first, by email (important!), to keep compatibility among JSON.pm
1808 backends.
1809
1810 =head1 SEE ALSO
1811
1812 L<JSON::XS>, L<Cpanel::JSON::XS>, L<JSON::PP> for backends.
1813
1814 L<JSON::MaybeXS>, an alternative that prefers Cpanel::JSON::XS.
1815
1816 C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
1817
1818 RFC7159 (L<http://www.ietf.org/rfc/rfc7159.txt>)
1819
1820 RFC8259 (L<http://www.ietf.org/rfc/rfc8259.txt>)
1821
1822 =head1 AUTHOR
1823
1824 Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
1825
1826 JSON::XS was written by Marc Lehmann E<lt>schmorp[at]schmorp.deE<gt>
1827
1828 The release of this new version owes to the courtesy of Marc Lehmann.
1829
1830 =head1 CURRENT MAINTAINER
1831
1832 Kenichi Ishigaki, E<lt>ishigaki[at]cpan.orgE<gt>
1833
1834 =head1 COPYRIGHT AND LICENSE
1835
1836 Copyright 2005-2013 by Makamaka Hannyaharamitu
1837
1838 Most of the documentation is taken from JSON::XS by Marc Lehmann
1839
1840 This library is free software; you can redistribute it and/or modify
1841 it under the same terms as Perl itself.
1842
1843 =cut
1844