source: main/trunk/greenstone2/perllib/cpan/JSON.pm@ 24921

Last change on this file since 24921 was 24921, checked in by davidb, 12 years ago

Some of our perl CGI scripts use JSON, while included in the ActivePerl distribution, it does not appear to be a standard Perl module

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