1 | package JSON;
|
---|
2 |
|
---|
3 |
|
---|
4 | use strict;
|
---|
5 | use Carp ();
|
---|
6 | use base qw(Exporter);
|
---|
7 | @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
|
---|
8 |
|
---|
9 | BEGIN {
|
---|
10 | $JSON::VERSION = '2.27';
|
---|
11 | $JSON::DEBUG = 0 unless (defined $JSON::DEBUG);
|
---|
12 | }
|
---|
13 |
|
---|
14 | my $Module_XS = 'JSON::XS';
|
---|
15 | my $Module_PP = 'JSON::PP';
|
---|
16 | my $XS_Version = '2.27';
|
---|
17 |
|
---|
18 |
|
---|
19 | # XS and PP common methods
|
---|
20 |
|
---|
21 | my @PublicMethods = qw/
|
---|
22 | ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref
|
---|
23 | allow_blessed convert_blessed filter_json_object filter_json_single_key_object
|
---|
24 | shrink max_depth max_size encode decode decode_prefix allow_unknown
|
---|
25 | /;
|
---|
26 |
|
---|
27 | my @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 |
|
---|
32 | my @XSOnlyMethods = qw//; # Currently nothing
|
---|
33 |
|
---|
34 | my @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)
|
---|
41 | my $_INSTALL_DONT_DIE = 1; # When _load_xs fails to load XS, don't die.
|
---|
42 | my $_INSTALL_ONLY = 2; # Don't call _set_methods()
|
---|
43 | my $_ALLOW_UNSUPPORTED = 0;
|
---|
44 | my $_UNIV_CONV_BLESSED = 0;
|
---|
45 |
|
---|
46 |
|
---|
47 | # Check the environment variable to decide worker module.
|
---|
48 |
|
---|
49 | unless ($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 |
|
---|
69 | sub 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 |
|
---|
109 | sub 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 |
|
---|
118 | sub 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 |
|
---|
130 | sub 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 |
|
---|
147 | sub 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 |
|
---|
164 | sub true { $JSON::true }
|
---|
165 |
|
---|
166 | sub false { $JSON::false }
|
---|
167 |
|
---|
168 | sub null { undef; }
|
---|
169 |
|
---|
170 |
|
---|
171 | sub require_xs_version { $XS_Version; }
|
---|
172 |
|
---|
173 | sub backend {
|
---|
174 | my $proto = shift;
|
---|
175 | $JSON::Backend;
|
---|
176 | }
|
---|
177 |
|
---|
178 | #*module = *backend;
|
---|
179 |
|
---|
180 |
|
---|
181 | sub is_xs {
|
---|
182 | return $_[0]->module eq $Module_XS;
|
---|
183 | }
|
---|
184 |
|
---|
185 |
|
---|
186 | sub is_pp {
|
---|
187 | return $_[0]->module eq $Module_PP;
|
---|
188 | }
|
---|
189 |
|
---|
190 |
|
---|
191 | sub pureperl_only_methods { @PPOnlyMethods; }
|
---|
192 |
|
---|
193 |
|
---|
194 | sub 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 |
|
---|
232 | sub _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 |
|
---|
265 | sub _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 |
|
---|
286 | sub _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 |
|
---|
316 | package JSON::Boolean;
|
---|
317 |
|
---|
318 | my %Installed;
|
---|
319 |
|
---|
320 | sub _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 |
|
---|
351 | package JSON::Backend::PP;
|
---|
352 |
|
---|
353 | sub 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 |
|
---|
367 | package JSON;
|
---|
368 |
|
---|
369 | 1;
|
---|
370 | __DATA__
|
---|
371 |
|
---|
372 |
|
---|
373 | #
|
---|
374 | # Helper classes for Backend Module (XS)
|
---|
375 | #
|
---|
376 |
|
---|
377 | package JSON::Backend::XS;
|
---|
378 |
|
---|
379 | use constant INDENT_LENGTH_FLAG => 15 << 12;
|
---|
380 |
|
---|
381 | use constant UNSUPPORTED_ENCODE_FLAG => {
|
---|
382 | ESCAPE_SLASH => 0x00000010,
|
---|
383 | ALLOW_BIGNUM => 0x00000020,
|
---|
384 | AS_NONBLESSED => 0x00000040,
|
---|
385 | EXPANDED => 0x10000000, # for developer's
|
---|
386 | };
|
---|
387 |
|
---|
388 | use 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 |
|
---|
397 | sub 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 |
|
---|
408 | sub 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 |
|
---|
461 | package JSON::Backend::XS::Supportable;
|
---|
462 |
|
---|
463 | $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
|
---|
464 |
|
---|
465 | sub _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 |
|
---|
489 | sub _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 |
|
---|
515 | sub _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 |
|
---|
525 | sub _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 |
|
---|
535 | sub decode_prefix { # if unsupported-flag is set, use PP
|
---|
536 | _set_for_pp('decode' => @_)->decode_prefix($_[1]);
|
---|
537 | }
|
---|
538 |
|
---|
539 |
|
---|
540 | sub _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 |
|
---|
550 | sub get_indent_length {
|
---|
551 | ${$_[0]} << 4 >> 16;
|
---|
552 | }
|
---|
553 |
|
---|
554 |
|
---|
555 | sub 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 |
|
---|
573 | 1;
|
---|
574 | __END__
|
---|
575 |
|
---|
576 | =head1 NAME
|
---|
577 |
|
---|
578 | JSON - 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 |
|
---|
616 | This 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 |
|
---|
628 | JSON (JavaScript Object Notation) is a simple data format.
|
---|
629 | See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
|
---|
630 |
|
---|
631 | This module converts Perl data structures to JSON and vice versa using either
|
---|
632 | L<JSON::XS> or L<JSON::PP>.
|
---|
633 |
|
---|
634 | JSON::XS is the fastest and most proper JSON module on CPAN which must be
|
---|
635 | compiled and installed in your environment.
|
---|
636 | JSON::PP is a pure-Perl module which is bundled in this distribution and
|
---|
637 | has a strong compatibility to JSON::XS.
|
---|
638 |
|
---|
639 | This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
|
---|
640 | So its features completely depend on JSON::XS or JSON::PP.
|
---|
641 |
|
---|
642 | See to L<BACKEND MODULE DECISION>.
|
---|
643 |
|
---|
644 | To distinguish the module name 'JSON' and the format type JSON,
|
---|
645 | the former is quoted by CE<lt>E<gt> (its results vary with your using media),
|
---|
646 | and the latter is left just as it is.
|
---|
647 |
|
---|
648 | Module name : C<JSON>
|
---|
649 |
|
---|
650 | Format type : JSON
|
---|
651 |
|
---|
652 | =head2 FEATURES
|
---|
653 |
|
---|
654 | =over
|
---|
655 |
|
---|
656 | =item * correct unicode handling
|
---|
657 |
|
---|
658 | This module (i.e. backend modules) knows how to handle Unicode, documents
|
---|
659 | how and when it does so, and even documents what "correct" means.
|
---|
660 |
|
---|
661 | Even though there are limitations, this feature is available since Perl version 5.6.
|
---|
662 |
|
---|
663 | JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
|
---|
664 | C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005.
|
---|
665 |
|
---|
666 | With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
|
---|
667 | JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
|
---|
668 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
|
---|
669 |
|
---|
670 | See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
|
---|
671 | and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
|
---|
672 |
|
---|
673 |
|
---|
674 | =item * round-trip integrity
|
---|
675 |
|
---|
676 | When you serialise a perl data structure using only data types supported
|
---|
677 | by JSON and Perl, the deserialised data structure is identical on the Perl
|
---|
678 | level. (e.g. the string "2.0" doesn't suddenly become "2" just because
|
---|
679 | it looks like a number). There I<are> minor exceptions to this, read the
|
---|
680 | L</MAPPING> section below to learn about those.
|
---|
681 |
|
---|
682 |
|
---|
683 | =item * strict checking of JSON correctness
|
---|
684 |
|
---|
685 | There is no guessing, no generating of illegal JSON texts by default,
|
---|
686 | and only JSON is accepted as input by default (the latter is a security
|
---|
687 | feature).
|
---|
688 |
|
---|
689 | See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
|
---|
690 |
|
---|
691 | =item * fast
|
---|
692 |
|
---|
693 | This module returns a JSON::XS object itself if available.
|
---|
694 | Compared to other JSON modules and other serialisers such as Storable,
|
---|
695 | JSON::XS usually compares favourably in terms of speed, too.
|
---|
696 |
|
---|
697 | If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
|
---|
698 | it is very slow as pure-Perl.
|
---|
699 |
|
---|
700 | =item * simple to use
|
---|
701 |
|
---|
702 | This module has both a simple functional interface as well as an
|
---|
703 | object oriented interface interface.
|
---|
704 |
|
---|
705 | =item * reasonably versatile output formats
|
---|
706 |
|
---|
707 | You 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
|
---|
709 | is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
|
---|
710 | format (for when you want to read that stuff). Or you can combine those features
|
---|
711 | in whatever way you like.
|
---|
712 |
|
---|
713 | =back
|
---|
714 |
|
---|
715 | =head1 FUNCTIONAL INTERFACE
|
---|
716 |
|
---|
717 | Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
|
---|
718 | C<to_json> and C<from_json> are additional functions.
|
---|
719 |
|
---|
720 | =head2 encode_json
|
---|
721 |
|
---|
722 | $json_text = encode_json $perl_scalar
|
---|
723 |
|
---|
724 | Converts the given Perl data structure to a UTF-8 encoded, binary string.
|
---|
725 |
|
---|
726 | This 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 |
|
---|
734 | The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
|
---|
735 | to parse that as an UTF-8 encoded JSON text, returning the resulting
|
---|
736 | reference.
|
---|
737 |
|
---|
738 | This 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 |
|
---|
747 | Converts the given Perl data structure to a json string.
|
---|
748 |
|
---|
749 | This function call is functionally identical to:
|
---|
750 |
|
---|
751 | $json_text = JSON->new->encode($perl_scalar)
|
---|
752 |
|
---|
753 | Takes a hash reference as the second.
|
---|
754 |
|
---|
755 | $json_text = to_json($perl_scalar, $flag_hashref)
|
---|
756 |
|
---|
757 | So,
|
---|
758 |
|
---|
759 | $json_text = encode_json($perl_scalar, {utf8 => 1, pretty => 1})
|
---|
760 |
|
---|
761 | equivalent to:
|
---|
762 |
|
---|
763 | $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
|
---|
764 |
|
---|
765 | If you want to write a modern perl code which communicates to outer world,
|
---|
766 | you 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 |
|
---|
772 | The opposite of C<to_json>: expects a json string and tries
|
---|
773 | to parse it, returning the resulting reference.
|
---|
774 |
|
---|
775 | This function call is functionally identical to:
|
---|
776 |
|
---|
777 | $perl_scalar = JSON->decode($json_text)
|
---|
778 |
|
---|
779 | Takes a hash reference as the second.
|
---|
780 |
|
---|
781 | $perl_scalar = from_json($json_text, $flag_hashref)
|
---|
782 |
|
---|
783 | So,
|
---|
784 |
|
---|
785 | $perl_scalar = from_json($json_text, {utf8 => 1})
|
---|
786 |
|
---|
787 | equivalent to:
|
---|
788 |
|
---|
789 | $perl_scalar = JSON->new->utf8(1)->decode($json_text)
|
---|
790 |
|
---|
791 | If you want to write a modern perl code which communicates to outer world,
|
---|
792 | you 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 |
|
---|
798 | Returns true if the passed scalar represents either JSON::true or
|
---|
799 | JSON::false, two constants that act like C<1> and C<0> respectively
|
---|
800 | and are also used to represent JSON C<true> and C<false> in Perl strings.
|
---|
801 |
|
---|
802 | =head2 JSON::true
|
---|
803 |
|
---|
804 | Returns JSON true value which is blessed object.
|
---|
805 | It C<isa> JSON::Boolean object.
|
---|
806 |
|
---|
807 | =head2 JSON::false
|
---|
808 |
|
---|
809 | Returns JSON false value which is blessed object.
|
---|
810 | It C<isa> JSON::Boolean object.
|
---|
811 |
|
---|
812 | =head2 JSON::null
|
---|
813 |
|
---|
814 | Returns C<undef>.
|
---|
815 |
|
---|
816 | See L<MAPPING>, below, for more information on how JSON values are mapped to
|
---|
817 | Perl.
|
---|
818 |
|
---|
819 | =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
|
---|
820 |
|
---|
821 | This section supposes that your perl vresion is 5.8 or later.
|
---|
822 |
|
---|
823 | If you know a JSON text from an outer world - a network, a file content, and so on,
|
---|
824 | is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
|
---|
825 | with 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 |
|
---|
838 | If 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 |
|
---|
851 | In this case, C<$unicode_json_text> is of course UNICODE string.
|
---|
852 | So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
|
---|
853 | Instead 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 |
|
---|
859 | Or 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 |
|
---|
864 | And now, you want to convert your C<$perl_scalar> into JSON data and
|
---|
865 | send it to an outer world - a network or a file content, and so on.
|
---|
866 |
|
---|
867 | Your data usually contains UNICODE strings and you want the converted data to be encoded
|
---|
868 | in 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 |
|
---|
874 | If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
|
---|
875 | for some reason, then its characters are regarded as B<latin1> for perl
|
---|
876 | (because it does not concern with your $encoding).
|
---|
877 | You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
|
---|
878 | Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
|
---|
879 | Note 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 |
|
---|
888 | Or 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 |
|
---|
894 | This method is a proper way but probably not efficient.
|
---|
895 |
|
---|
896 | See to L<Encode>, L<perluniintro>.
|
---|
897 |
|
---|
898 |
|
---|
899 | =head1 COMMON OBJECT-ORIENTED INTERFACE
|
---|
900 |
|
---|
901 | =head2 new
|
---|
902 |
|
---|
903 | $json = new JSON
|
---|
904 |
|
---|
905 | Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
|
---|
906 | that can be used to de/encode JSON strings.
|
---|
907 |
|
---|
908 | All boolean flags described below are by default I<disabled>.
|
---|
909 |
|
---|
910 | The mutators for flags all return the JSON object again and thus calls can
|
---|
911 | be 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 |
|
---|
922 | If $enable is true (or missing), then the encode method will not generate characters outside
|
---|
923 | the code range 0..127. Any Unicode characters outside that range will be escaped using either
|
---|
924 | a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
|
---|
925 |
|
---|
926 | If $enable is false, then the encode method will not escape Unicode characters unless
|
---|
927 | required by the JSON syntax or other flags. This results in a faster and more compact format.
|
---|
928 |
|
---|
929 | This feature depends on the used Perl version and environment.
|
---|
930 |
|
---|
931 | See 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 |
|
---|
942 | If $enable is true (or missing), then the encode method will encode the resulting JSON
|
---|
943 | text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
|
---|
944 |
|
---|
945 | If $enable is false, then the encode method will not escape Unicode characters
|
---|
946 | unless 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 |
|
---|
957 | If $enable is true (or missing), then the encode method will encode the JSON result
|
---|
958 | into UTF-8, as required by many protocols, while the decode method expects to be handled
|
---|
959 | an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
|
---|
960 | characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
|
---|
961 |
|
---|
962 | In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
|
---|
963 | encoding families, as described in RFC4627.
|
---|
964 |
|
---|
965 | If $enable is false, then the encode method will return the JSON string as a (non-encoded)
|
---|
966 | Unicode 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 |
|
---|
970 | Example, output UTF-16BE-encoded JSON:
|
---|
971 |
|
---|
972 | use Encode;
|
---|
973 | $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
|
---|
974 |
|
---|
975 | Example, decode UTF-32LE-encoded JSON:
|
---|
976 |
|
---|
977 | use Encode;
|
---|
978 | $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
|
---|
979 |
|
---|
980 | See 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 |
|
---|
987 | This enables (or disables) all of the C<indent>, C<space_before> and
|
---|
988 | C<space_after> (and in the future possibly more) flags in one call to
|
---|
989 | generate the most readable (or most compact) form possible.
|
---|
990 |
|
---|
991 | Equivalent to:
|
---|
992 |
|
---|
993 | $json->indent->space_before->space_after
|
---|
994 |
|
---|
995 | The indent space length is three and JSON::XS cannot change the indent
|
---|
996 | space length.
|
---|
997 |
|
---|
998 | =head2 indent
|
---|
999 |
|
---|
1000 | $json = $json->indent([$enable])
|
---|
1001 |
|
---|
1002 | $enabled = $json->get_indent
|
---|
1003 |
|
---|
1004 | If C<$enable> is true (or missing), then the C<encode> method will use a multiline
|
---|
1005 | format as output, putting every array member or object/hash key-value pair
|
---|
1006 | into its own line, identing them properly.
|
---|
1007 |
|
---|
1008 | If C<$enable> is false, no newlines or indenting will be produced, and the
|
---|
1009 | resulting JSON text is guarenteed not to contain any C<newlines>.
|
---|
1010 |
|
---|
1011 | This setting has no effect when decoding JSON texts.
|
---|
1012 |
|
---|
1013 | The indent space length is three.
|
---|
1014 | With 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 |
|
---|
1023 | If C<$enable> is true (or missing), then the C<encode> method will add an extra
|
---|
1024 | optional space before the C<:> separating keys from values in JSON objects.
|
---|
1025 |
|
---|
1026 | If C<$enable> is false, then the C<encode> method will not add any extra
|
---|
1027 | space at those places.
|
---|
1028 |
|
---|
1029 | This setting has no effect when decoding JSON texts.
|
---|
1030 |
|
---|
1031 | Example, 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 |
|
---|
1042 | If C<$enable> is true (or missing), then the C<encode> method will add an extra
|
---|
1043 | optional space after the C<:> separating keys from values in JSON objects
|
---|
1044 | and extra whitespace after the C<,> separating key-value pairs and array
|
---|
1045 | members.
|
---|
1046 |
|
---|
1047 | If C<$enable> is false, then the C<encode> method will not add any extra
|
---|
1048 | space at those places.
|
---|
1049 |
|
---|
1050 | This setting has no effect when decoding JSON texts.
|
---|
1051 |
|
---|
1052 | Example, 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 |
|
---|
1063 | If C<$enable> is true (or missing), then C<decode> will accept some
|
---|
1064 | extensions to normal JSON syntax (see below). C<encode> will not be
|
---|
1065 | affected in anyway. I<Be aware that this option makes you accept invalid
|
---|
1066 | JSON texts as if they were valid!>. I suggest only to use this option to
|
---|
1067 | parse application-specific files written by humans (configuration files,
|
---|
1068 | resource files etc.)
|
---|
1069 |
|
---|
1070 | If C<$enable> is false (the default), then C<decode> will only accept
|
---|
1071 | valid JSON texts.
|
---|
1072 |
|
---|
1073 | Currently accepted extensions are:
|
---|
1074 |
|
---|
1075 | =over 4
|
---|
1076 |
|
---|
1077 | =item * list items can have an end-comma
|
---|
1078 |
|
---|
1079 | JSON I<separates> array elements and key-value pairs with commas. This
|
---|
1080 | can be annoying if you write JSON texts manually and want to be able to
|
---|
1081 | quickly append elements, so this extension accepts comma at the end of
|
---|
1082 | such 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 |
|
---|
1095 | Whenever JSON allows whitespace, shell-style comments are additionally
|
---|
1096 | allowed. They are terminated by the first carriage-return or line-feed
|
---|
1097 | character, 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 |
|
---|
1113 | If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
|
---|
1114 | by sorting their keys. This is adding a comparatively high overhead.
|
---|
1115 |
|
---|
1116 | If C<$enable> is false, then the C<encode> method will output key-value
|
---|
1117 | pairs in the order Perl stores them (which will likely change between runs
|
---|
1118 | of the same script).
|
---|
1119 |
|
---|
1120 | This option is useful if you want the same data structure to be encoded as
|
---|
1121 | the same JSON text (given the same overall settings). If it is disabled,
|
---|
1122 | the same hash might be encoded differently even if contains the same data,
|
---|
1123 | as key-value pairs have no inherent ordering in Perl.
|
---|
1124 |
|
---|
1125 | This 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 |
|
---|
1133 | If C<$enable> is true (or missing), then the C<encode> method can convert a
|
---|
1134 | non-reference into its corresponding string, number or null JSON value,
|
---|
1135 | which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
|
---|
1136 | values instead of croaking.
|
---|
1137 |
|
---|
1138 | If C<$enable> is false, then the C<encode> method will croak if it isn't
|
---|
1139 | passed an arrayref or hashref, as JSON texts must either be an object
|
---|
1140 | or array. Likewise, C<decode> will croak if given something that is not a
|
---|
1141 | JSON 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 |
|
---|
1152 | If $enable is true (or missing), then "encode" will *not* throw an
|
---|
1153 | exception when it encounters values it cannot represent in JSON (for
|
---|
1154 | example, filehandles) but instead will encode a JSON "null" value.
|
---|
1155 | Note that blessed objects are not included here and are handled
|
---|
1156 | separately by c<allow_nonref>.
|
---|
1157 |
|
---|
1158 | If $enable is false (the default), then "encode" will throw an
|
---|
1159 | exception when it encounters anything it cannot encode as JSON.
|
---|
1160 |
|
---|
1161 | This option does not affect "decode" in any way, and it is
|
---|
1162 | recommended to leave it off unless you know your communications
|
---|
1163 | partner.
|
---|
1164 |
|
---|
1165 | =head2 allow_blessed
|
---|
1166 |
|
---|
1167 | $json = $json->allow_blessed([$enable])
|
---|
1168 |
|
---|
1169 | $enabled = $json->get_allow_blessed
|
---|
1170 |
|
---|
1171 | If C<$enable> is true (or missing), then the C<encode> method will not
|
---|
1172 | barf when it encounters a blessed reference. Instead, the value of the
|
---|
1173 | B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
|
---|
1174 | disabled or no C<TO_JSON> method found) or a representation of the
|
---|
1175 | object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
|
---|
1176 | encoded. Has no effect on C<decode>.
|
---|
1177 |
|
---|
1178 | If C<$enable> is false (the default), then C<encode> will throw an
|
---|
1179 | exception 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 |
|
---|
1188 | If C<$enable> is true (or missing), then C<encode>, upon encountering a
|
---|
1189 | blessed object, will check for the availability of the C<TO_JSON> method
|
---|
1190 | on the object's class. If found, it will be called in scalar context
|
---|
1191 | and the resulting scalar will be encoded instead of the object. If no
|
---|
1192 | C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
|
---|
1193 | to do.
|
---|
1194 |
|
---|
1195 | The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
|
---|
1196 | returns other blessed objects, those will be handled in the same
|
---|
1197 | way. 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
|
---|
1199 | methods called by the Perl core (== not by the user of the object) are
|
---|
1200 | usually in upper case letters and to avoid collisions with the C<to_json>
|
---|
1201 | function or method.
|
---|
1202 |
|
---|
1203 | This setting does not yet influence C<decode> in any way.
|
---|
1204 |
|
---|
1205 | If C<$enable> is false, then the C<allow_blessed> setting will decide what
|
---|
1206 | to do when a blessed object is found.
|
---|
1207 |
|
---|
1208 | =over
|
---|
1209 |
|
---|
1210 | =item convert_blessed_universally mode
|
---|
1211 |
|
---|
1212 | If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
|
---|
1213 | subroutine 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 |
|
---|
1223 | This will cause that C<encode> method converts simple blessed objects into
|
---|
1224 | JSON objects as non-blessed object.
|
---|
1225 |
|
---|
1226 | JSON -convert_blessed_universally;
|
---|
1227 | $json->allow_blessed->convert_blessed->encode( $blessed_object )
|
---|
1228 |
|
---|
1229 | This 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 |
|
---|
1237 | When C<$coderef> is specified, it will be called from C<decode> each
|
---|
1238 | time it decodes a JSON object. The only argument passed to the coderef
|
---|
1239 | is a reference to the newly-created hash. If the code references returns
|
---|
1240 | a 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
|
---|
1242 | deserialised data structure. If it returns an empty list
|
---|
1243 | (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
|
---|
1244 | hash will be inserted. This setting can slow down decoding considerably.
|
---|
1245 |
|
---|
1246 | When C<$coderef> is omitted or undefined, any existing callback will
|
---|
1247 | be removed and C<decode> will not change the deserialised hash in any
|
---|
1248 | way.
|
---|
1249 |
|
---|
1250 | Example, 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 |
|
---|
1264 | Works remotely similar to C<filter_json_object>, but is only called for
|
---|
1265 | JSON objects having a single key named C<$key>.
|
---|
1266 |
|
---|
1267 | This C<$coderef> is called before the one specified via
|
---|
1268 | C<filter_json_object>, if any. It gets passed the single value in the JSON
|
---|
1269 | object. If it returns a single value, it will be inserted into the data
|
---|
1270 | structure. If it returns nothing (not even C<undef> but the empty list),
|
---|
1271 | the callback from C<filter_json_object> will be called next, as if no
|
---|
1272 | single-key callback were specified.
|
---|
1273 |
|
---|
1274 | If C<$coderef> is omitted or undefined, the corresponding callback will be
|
---|
1275 | disabled. There can only ever be one callback for a given key.
|
---|
1276 |
|
---|
1277 | As this callback gets called less often then the C<filter_json_object>
|
---|
1278 | one, decoding speed will not usually suffer as much. Therefore, single-key
|
---|
1279 | objects make excellent targets to serialise Perl objects into, especially
|
---|
1280 | as single-key JSON objects are as close to the type-tagged value concept
|
---|
1281 | as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
|
---|
1282 | support this in any way, so you need to make sure your data never looks
|
---|
1283 | like a serialised Perl hash.
|
---|
1284 |
|
---|
1285 | Typical names for the single object key are C<__class_whatever__>, or
|
---|
1286 | C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
|
---|
1287 | things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
|
---|
1288 | with real hashes.
|
---|
1289 |
|
---|
1290 | Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
|
---|
1291 | into 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 |
|
---|
1321 | With JSON::XS, this flag resizes strings generated by either
|
---|
1322 | C<encode> or C<decode> to their minimum size possible. This can save
|
---|
1323 | memory when your JSON texts are either very very long or you have many
|
---|
1324 | short strings. It will also try to downgrade any strings to octet-form
|
---|
1325 | if possible: perl stores strings internally either in an encoding called
|
---|
1326 | UTF-X or in octet-form. The latter cannot store everything but uses less
|
---|
1327 | space in general (and some buggy Perl or C code might even rely on that
|
---|
1328 | internal representation being used).
|
---|
1329 |
|
---|
1330 | With JSON::PP, it is noop about resizing strings but tries
|
---|
1331 | C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
|
---|
1332 |
|
---|
1333 | See 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 |
|
---|
1341 | Sets the maximum nesting level (default C<512>) accepted while encoding
|
---|
1342 | or decoding. If a higher nesting level is detected in JSON text or a Perl
|
---|
1343 | data structure, then the encoder and decoder will stop and croak at that
|
---|
1344 | point.
|
---|
1345 |
|
---|
1346 | Nesting level is defined by number of hash- or arrayrefs that the encoder
|
---|
1347 | needs to traverse to reach a given point or the number of C<{> or C<[>
|
---|
1348 | characters without their matching closing parenthesis crossed to reach a
|
---|
1349 | given character in a string.
|
---|
1350 |
|
---|
1351 | If no argument is given, the highest possible setting will be used, which
|
---|
1352 | is rarely useful.
|
---|
1353 |
|
---|
1354 | Note that nesting is implemented by recursion in C. The default value has
|
---|
1355 | been chosen to be as large as typical operating systems allow without
|
---|
1356 | crashing. (JSON::XS)
|
---|
1357 |
|
---|
1358 | With JSON::PP as the backend, when a large value (100 or more) was set and
|
---|
1359 | it de/encodes a deep nested object/text, it may raise a warning
|
---|
1360 | 'Deep recursion on subroutin' at the perl runtime phase.
|
---|
1361 |
|
---|
1362 | See 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 |
|
---|
1370 | Set the maximum length a JSON text may have (in bytes) where decoding is
|
---|
1371 | being attempted. The default is C<0>, meaning no limit. When C<decode>
|
---|
1372 | is called on a string that is longer then this many bytes, it will not
|
---|
1373 | attempt to decode the string but throw an exception. This setting has no
|
---|
1374 | effect on C<encode> (yet).
|
---|
1375 |
|
---|
1376 | If no argument is given, the limit check will be deactivated (same as when
|
---|
1377 | C<0> is specified).
|
---|
1378 |
|
---|
1379 | See 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 |
|
---|
1385 | Converts the given Perl data structure (a simple scalar or a reference
|
---|
1386 | to a hash or array) to its JSON representation. Simple scalars will be
|
---|
1387 | converted into JSON string or number sequences, while references to arrays
|
---|
1388 | become JSON arrays and references to hashes become JSON objects. Undefined
|
---|
1389 | Perl values (e.g. C<undef>) become JSON C<null> values.
|
---|
1390 | References 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 |
|
---|
1396 | The opposite of C<encode>: expects a JSON text and tries to parse it,
|
---|
1397 | returning the resulting simple scalar or reference. Croaks on error.
|
---|
1398 |
|
---|
1399 | JSON numbers and strings become simple Perl scalars. JSON arrays become
|
---|
1400 | Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
|
---|
1401 | C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
|
---|
1402 | C<null> becomes C<undef>.
|
---|
1403 |
|
---|
1404 | =head2 decode_prefix
|
---|
1405 |
|
---|
1406 | ($perl_scalar, $characters) = $json->decode_prefix($json_text)
|
---|
1407 |
|
---|
1408 | This works like the C<decode> method, but instead of raising an exception
|
---|
1409 | when there is trailing garbage after the first JSON object, it will
|
---|
1410 | silently stop parsing there and return the number of characters consumed
|
---|
1411 | so far.
|
---|
1412 |
|
---|
1413 | JSON->new->decode_prefix ("[1] the tail")
|
---|
1414 | => ([], 3)
|
---|
1415 |
|
---|
1416 | See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
|
---|
1417 |
|
---|
1418 | =head2 property
|
---|
1419 |
|
---|
1420 | $boolean = $json->property($property_name)
|
---|
1421 |
|
---|
1422 | Returns a boolean value about above some properties.
|
---|
1423 |
|
---|
1424 | The available properties are C<ascii>, C<latin1>, C<utf8>,
|
---|
1425 | C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
|
---|
1426 | C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
|
---|
1427 | C<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 |
|
---|
1435 | Sets the property with a given boolean value.
|
---|
1436 |
|
---|
1437 | $json = $json->property($property_name => $boolean);
|
---|
1438 |
|
---|
1439 | With no argumnt, it returns all the above properties as a hash reference.
|
---|
1440 |
|
---|
1441 | $flag_hashref = $json->property();
|
---|
1442 |
|
---|
1443 | =head1 INCREMENTAL PARSING
|
---|
1444 |
|
---|
1445 | Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
|
---|
1446 |
|
---|
1447 | In some cases, there is the need for incremental parsing of JSON texts.
|
---|
1448 | This module does allow you to parse a JSON stream incrementally.
|
---|
1449 | It does so by accumulating text until it has a full JSON object, which
|
---|
1450 | it then can decode. This process is similar to using C<decode_prefix>
|
---|
1451 | to 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 |
|
---|
1454 | The backend module will only attempt to parse the JSON text once it is sure it
|
---|
1455 | has enough text to get a decisive result, using a very simple but
|
---|
1456 | truly incremental parser. This means that it sometimes won't stop as
|
---|
1457 | early as the full parser, for example, it doesn't detect parenthese
|
---|
1458 | mismatches. The only thing it guarantees is that it starts decoding as
|
---|
1459 | soon as a syntactically valid JSON text has been seen. This means you need
|
---|
1460 | to set resource limits (e.g. C<max_size>) to ensure the parser will stop
|
---|
1461 | parsing in the presence if syntax errors.
|
---|
1462 |
|
---|
1463 | The 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 |
|
---|
1473 | This is the central parsing function. It can both append new text and
|
---|
1474 | extract objects from the stream accumulated so far (both of these
|
---|
1475 | functions are optional).
|
---|
1476 |
|
---|
1477 | If C<$string> is given, then this string is appended to the already
|
---|
1478 | existing JSON fragment stored in the C<$json> object.
|
---|
1479 |
|
---|
1480 | After that, if the function is called in void context, it will simply
|
---|
1481 | return without doing anything further. This can be used to add more text
|
---|
1482 | in as many chunks as you want.
|
---|
1483 |
|
---|
1484 | If the method is called in scalar context, then it will try to extract
|
---|
1485 | exactly I<one> JSON object. If that is successful, it will return this
|
---|
1486 | object, otherwise it will return C<undef>. If there is a parse error,
|
---|
1487 | this method will croak just as C<decode> would do (one can then use
|
---|
1488 | C<incr_skip> to skip the errornous part). This is the most common way of
|
---|
1489 | using the method.
|
---|
1490 |
|
---|
1491 | And finally, in list context, it will try to extract as many objects
|
---|
1492 | from the stream as it can find and return them, or the empty list
|
---|
1493 | otherwise. For this to work, there must be no separators between the JSON
|
---|
1494 | objects or arrays, instead they must be concatenated back-to-back. If
|
---|
1495 | an error occurs, an exception will be raised as in the scalar context
|
---|
1496 | case. Note that in this case, any previously-parsed JSON texts will be
|
---|
1497 | lost.
|
---|
1498 |
|
---|
1499 | Example: 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 |
|
---|
1507 | This method returns the currently stored JSON fragment as an lvalue, that
|
---|
1508 | is, you can manipulate it. This I<only> works when a preceding call to
|
---|
1509 | C<incr_parse> in I<scalar context> successfully returned an object. Under
|
---|
1510 | all other circumstances you must not call this function (I mean it.
|
---|
1511 | although in simple tests it might actually work, it I<will> fail under
|
---|
1512 | real world conditions). As a special exception, you can also call this
|
---|
1513 | method before having parsed anything.
|
---|
1514 |
|
---|
1515 | This function is useful in two cases: a) finding the trailing text after a
|
---|
1516 | JSON 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 |
|
---|
1521 | In Perl 5.005, C<lvalue> attribute is not available.
|
---|
1522 | You 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 |
|
---|
1532 | This will reset the state of the incremental parser and will remove the
|
---|
1533 | parsed text from the input buffer. This is useful after C<incr_parse>
|
---|
1534 | died, in which case the input buffer and incremental parser state is left
|
---|
1535 | unchanged, to skip the text parsed so far and to reset the parse state.
|
---|
1536 |
|
---|
1537 | =head2 incr_reset
|
---|
1538 |
|
---|
1539 | $json->incr_reset
|
---|
1540 |
|
---|
1541 | This completely resets the incremental parser, that is, after this call,
|
---|
1542 | it will be as if the parser had never parsed anything.
|
---|
1543 |
|
---|
1544 | This is useful if you want ot repeatedly parse JSON objects and want to
|
---|
1545 | ignore any trailing data, which means you have to reset the parser after
|
---|
1546 | each successful decode.
|
---|
1547 |
|
---|
1548 | See to L<JSON::XS/INCREMENTAL PARSING> for examples.
|
---|
1549 |
|
---|
1550 |
|
---|
1551 | =head1 JSON::PP SUPPORT METHODS
|
---|
1552 |
|
---|
1553 | The below methods are JSON::PP own methods, so when C<JSON> works
|
---|
1554 | with JSON::PP (i.e. the created object is a JSON::PP object), available.
|
---|
1555 | See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
|
---|
1556 |
|
---|
1557 | If you use C<JSON> with additonal C<-support_by_pp>, some methods
|
---|
1558 | are 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 |
|
---|
1571 | If you do not want to all functions but C<-support_by_pp>,
|
---|
1572 | use 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 |
|
---|
1581 | If C<$enable> is true (or missing), then C<decode> will accept
|
---|
1582 | any JSON strings quoted by single quotations that are invalid JSON
|
---|
1583 | format.
|
---|
1584 |
|
---|
1585 | $json->allow_singlequote->decode({"foo":'bar'});
|
---|
1586 | $json->allow_singlequote->decode({'foo':"bar"});
|
---|
1587 | $json->allow_singlequote->decode({'foo':'bar'});
|
---|
1588 |
|
---|
1589 | As same as the C<relaxed> option, this option may be used to parse
|
---|
1590 | application-specific files written by humans.
|
---|
1591 |
|
---|
1592 | =head2 allow_barekey
|
---|
1593 |
|
---|
1594 | $json = $json->allow_barekey([$enable])
|
---|
1595 |
|
---|
1596 | If C<$enable> is true (or missing), then C<decode> will accept
|
---|
1597 | bare keys of JSON object that are invalid JSON format.
|
---|
1598 |
|
---|
1599 | As same as the C<relaxed> option, this option may be used to parse
|
---|
1600 | application-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 |
|
---|
1608 | If C<$enable> is true (or missing), then C<decode> will convert
|
---|
1609 | the big integer Perl cannot handle as integer into a L<Math::BigInt>
|
---|
1610 | object and convert a floating number (any) into a L<Math::BigFloat>.
|
---|
1611 |
|
---|
1612 | On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
|
---|
1613 | objects 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 |
|
---|
1620 | See to L<MAPPING> aboout the conversion of JSON number.
|
---|
1621 |
|
---|
1622 | =head2 loose
|
---|
1623 |
|
---|
1624 | $json = $json->loose([$enable])
|
---|
1625 |
|
---|
1626 | The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
|
---|
1627 | and the module doesn't allow to C<decode> to these (except for \x2f).
|
---|
1628 | If C<$enable> is true (or missing), then C<decode> will accept these
|
---|
1629 | unescaped strings.
|
---|
1630 |
|
---|
1631 | $json->loose->decode(qq|["abc
|
---|
1632 | def"]|);
|
---|
1633 |
|
---|
1634 | See to L<JSON::PP/JSON::PP OWN METHODS>.
|
---|
1635 |
|
---|
1636 | =head2 escape_slash
|
---|
1637 |
|
---|
1638 | $json = $json->escape_slash([$enable])
|
---|
1639 |
|
---|
1640 | According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
|
---|
1641 | JSON backend modules encode strings without escaping slash.
|
---|
1642 |
|
---|
1643 | If 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 |
|
---|
1649 | With JSON::XS, The indent space length is 3 and cannot be changed.
|
---|
1650 | With JSON::PP, it sets the indent space length with the given $length.
|
---|
1651 | The 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 |
|
---|
1658 | If $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 |
|
---|
1668 | As the sorting routine runs in the JSON::PP scope, the given
|
---|
1669 | subroutine name and the special variables C<$a>, C<$b> will begin
|
---|
1670 | with 'JSON::PP::'.
|
---|
1671 |
|
---|
1672 | If $integer is set, then the effect is same as C<canonical> on.
|
---|
1673 |
|
---|
1674 | See to L<JSON::PP/JSON::PP OWN METHODS>.
|
---|
1675 |
|
---|
1676 | =head1 MAPPING
|
---|
1677 |
|
---|
1678 | This section is copied from JSON::XS and modified to C<JSON>.
|
---|
1679 | JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
|
---|
1680 |
|
---|
1681 | See to L<JSON::XS/MAPPING>.
|
---|
1682 |
|
---|
1683 | =head2 JSON -> PERL
|
---|
1684 |
|
---|
1685 | =over 4
|
---|
1686 |
|
---|
1687 | =item object
|
---|
1688 |
|
---|
1689 | A JSON object becomes a reference to a hash in Perl. No ordering of object
|
---|
1690 | keys is preserved (JSON does not preserver object key ordering itself).
|
---|
1691 |
|
---|
1692 | =item array
|
---|
1693 |
|
---|
1694 | A JSON array becomes a reference to an array in Perl.
|
---|
1695 |
|
---|
1696 | =item string
|
---|
1697 |
|
---|
1698 | A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
|
---|
1699 | are represented by the same codepoints in the Perl string, so no manual
|
---|
1700 | decoding is necessary.
|
---|
1701 |
|
---|
1702 | =item number
|
---|
1703 |
|
---|
1704 | A JSON number becomes either an integer, numeric (floating point) or
|
---|
1705 | string scalar in perl, depending on its range and any fractional parts. On
|
---|
1706 | the Perl level, there is no difference between those as Perl handles all
|
---|
1707 | the conversion details, but an integer may take slightly less memory and
|
---|
1708 | might represent more values exactly than floating point numbers.
|
---|
1709 |
|
---|
1710 | If the number consists of digits only, C<JSON> will try to represent
|
---|
1711 | it as an integer value. If that fails, it will try to represent it as
|
---|
1712 | a numeric (floating point) value if that is possible without loss of
|
---|
1713 | precision. Otherwise it will preserve the number as a string value (in
|
---|
1714 | which case you lose roundtripping ability, as the JSON number will be
|
---|
1715 | re-encoded toa JSON string).
|
---|
1716 |
|
---|
1717 | Numbers containing a fractional or exponential part will always be
|
---|
1718 | represented as numeric (floating point) values, possibly at a loss of
|
---|
1719 | precision (in which case you might lose perfect roundtripping ability, but
|
---|
1720 | the JSON number will still be re-encoded as a JSON number).
|
---|
1721 |
|
---|
1722 | Note that precision is not accuracy - binary floating point values cannot
|
---|
1723 | represent most decimal fractions exactly, and when converting from and to
|
---|
1724 | floating point, C<JSON> only guarantees precision up to but not including
|
---|
1725 | the leats significant bit.
|
---|
1726 |
|
---|
1727 | If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
|
---|
1728 | and the numeric can be optionally converted into L<Math::BigInt> and
|
---|
1729 | L<Math::BigFloat> objects.
|
---|
1730 |
|
---|
1731 | =item true, false
|
---|
1732 |
|
---|
1733 | These JSON atoms become C<JSON::true> and C<JSON::false>,
|
---|
1734 | respectively. They are overloaded to act almost exactly like the numbers
|
---|
1735 | C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
|
---|
1736 | the C<JSON::is_bool> function.
|
---|
1737 |
|
---|
1738 | If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
|
---|
1739 | they 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 |
|
---|
1750 | C<JSON> will install these missing overloading features to the backend modules.
|
---|
1751 |
|
---|
1752 |
|
---|
1753 | =item null
|
---|
1754 |
|
---|
1755 | A JSON null atom becomes C<undef> in Perl.
|
---|
1756 |
|
---|
1757 | C<JSON::null> returns C<unddef>.
|
---|
1758 |
|
---|
1759 | =back
|
---|
1760 |
|
---|
1761 |
|
---|
1762 | =head2 PERL -> JSON
|
---|
1763 |
|
---|
1764 | The mapping from Perl to JSON is slightly more difficult, as Perl is a
|
---|
1765 | truly typeless language, so we can only guess which JSON type is meant by
|
---|
1766 | a Perl value.
|
---|
1767 |
|
---|
1768 | =over 4
|
---|
1769 |
|
---|
1770 | =item hash references
|
---|
1771 |
|
---|
1772 | Perl hash references become JSON objects. As there is no inherent ordering
|
---|
1773 | in hash keys (or JSON objects), they will usually be encoded in a
|
---|
1774 | pseudo-random order that can change between runs of the same program but
|
---|
1775 | stays generally the same within a single run of a program. C<JSON>
|
---|
1776 | optionally sort the hash keys (determined by the I<canonical> flag), so
|
---|
1777 | the same datastructure will serialise to the same JSON text (given same
|
---|
1778 | settings and version of JSON::XS), but this incurs a runtime overhead
|
---|
1779 | and is only rarely useful, e.g. when you want to compare some JSON text
|
---|
1780 | against another for equality.
|
---|
1781 |
|
---|
1782 | In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
|
---|
1783 |
|
---|
1784 |
|
---|
1785 | =item array references
|
---|
1786 |
|
---|
1787 | Perl array references become JSON arrays.
|
---|
1788 |
|
---|
1789 | =item other references
|
---|
1790 |
|
---|
1791 | Other unblessed references are generally not allowed and will cause an
|
---|
1792 | exception to be thrown, except for references to the integers C<0> and
|
---|
1793 | C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
|
---|
1794 | also 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 |
|
---|
1800 | These special values become JSON true and JSON false values,
|
---|
1801 | respectively. You can also use C<\1> and C<\0> directly if you want.
|
---|
1802 |
|
---|
1803 | JSON::null returns C<undef>.
|
---|
1804 |
|
---|
1805 | =item blessed objects
|
---|
1806 |
|
---|
1807 | Blessed objects are not directly representable in JSON. See the
|
---|
1808 | C<allow_blessed> and C<convert_blessed> methods on various options on
|
---|
1809 | how to deal with this: basically, you can choose between throwing an
|
---|
1810 | exception, encoding the reference as if it weren't blessed, or provide
|
---|
1811 | your own serialiser method.
|
---|
1812 |
|
---|
1813 | With C<convert_blessed_universally> mode, C<encode> converts blessed
|
---|
1814 | hash references or blessed array references (contains other blessed references)
|
---|
1815 | into JSON members and arrays.
|
---|
1816 |
|
---|
1817 | use JSON -convert_blessed_universally;
|
---|
1818 | JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
|
---|
1819 |
|
---|
1820 | See to L<convert_blessed>.
|
---|
1821 |
|
---|
1822 | =item simple scalars
|
---|
1823 |
|
---|
1824 | Simple Perl scalars (any scalar that is not a reference) are the most
|
---|
1825 | difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
|
---|
1826 | JSON C<null> values, scalars that have last been used in a string context
|
---|
1827 | before 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 |
|
---|
1841 | You 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 |
|
---|
1848 | You 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 |
|
---|
1854 | You can not currently force the type in other, less obscure, ways.
|
---|
1855 |
|
---|
1856 | Note that numerical precision has the same meaning as under Perl (so
|
---|
1857 | binary to decimal conversion follows the same rules as in Perl, which
|
---|
1858 | can differ to other languages). Also, your perl interpreter might expose
|
---|
1859 | extensions to the floating point numbers of your platform, such as
|
---|
1860 | infinities or NaN's - these cannot be represented in JSON, and it is an
|
---|
1861 | error to pass those in.
|
---|
1862 |
|
---|
1863 | =item Big Number
|
---|
1864 |
|
---|
1865 | If the backend is JSON::PP and C<allow_bignum> is enable,
|
---|
1866 | C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
|
---|
1867 | objects into JSON numbers.
|
---|
1868 |
|
---|
1869 |
|
---|
1870 | =back
|
---|
1871 |
|
---|
1872 | =head1 JSON and ECMAscript
|
---|
1873 |
|
---|
1874 | See to L<JSON::XS/JSON and ECMAscript>.
|
---|
1875 |
|
---|
1876 | =head1 JSON and YAML
|
---|
1877 |
|
---|
1878 | JSON is not a subset of YAML.
|
---|
1879 | See to L<JSON::XS/JSON and YAML>.
|
---|
1880 |
|
---|
1881 |
|
---|
1882 | =head1 BACKEND MODULE DECISION
|
---|
1883 |
|
---|
1884 | When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
|
---|
1885 | C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
|
---|
1886 |
|
---|
1887 | The C<JSON> constructor method returns an object inherited from the backend module,
|
---|
1888 | and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash
|
---|
1889 | reference.
|
---|
1890 |
|
---|
1891 | So, your program should not depend on the backend module, especially
|
---|
1892 | returned 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 |
|
---|
1897 | To 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 |
|
---|
1910 | If 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 |
|
---|
1916 | Always 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,
|
---|
1921 | otherwise use JSON::PP.
|
---|
1922 |
|
---|
1923 | =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
|
---|
1924 |
|
---|
1925 | Always use compiled JSON::XS, die if it isn't properly compiled & installed.
|
---|
1926 |
|
---|
1927 | =back
|
---|
1928 |
|
---|
1929 | These ideas come from L<DBI::PurePerl> mechanism.
|
---|
1930 |
|
---|
1931 | example:
|
---|
1932 |
|
---|
1933 | BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
|
---|
1934 | use JSON; # always uses JSON::PP
|
---|
1935 |
|
---|
1936 | In future, it may be able to specify another module.
|
---|
1937 |
|
---|
1938 | =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
|
---|
1939 |
|
---|
1940 | Many methods are available with either JSON::XS or JSON::PP and
|
---|
1941 | when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported)
|
---|
1942 | method is called, it will C<warn> and be noop.
|
---|
1943 |
|
---|
1944 | But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
|
---|
1945 | it makes a part of those unupported methods available.
|
---|
1946 | This 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 |
|
---|
1953 | At this time, the returned object is a C<JSON::Backend::XS::Supportable>
|
---|
1954 | object (re-blessed XS object), and by checking JSON::XS unsupported flags
|
---|
1955 | in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
|
---|
1956 | C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
|
---|
1957 |
|
---|
1958 | When any unsupported methods are not enable, C<XS de/encode> will be
|
---|
1959 | used as is. The switch is achieved by changing the symbolic tables.
|
---|
1960 |
|
---|
1961 | C<-support_by_pp> is effective only when the backend module is JSON::XS
|
---|
1962 | and it makes the de/encoding speed down a bit.
|
---|
1963 |
|
---|
1964 | See to L<JSON::PP SUPPORT METHODS>.
|
---|
1965 |
|
---|
1966 | =head1 INCOMPATIBLE CHANGES TO OLD VERSION
|
---|
1967 |
|
---|
1968 | There are big incompatibility between new version (2.00) and old (1.xx).
|
---|
1969 | If you use old C<JSON> 1.xx in your code, please check it.
|
---|
1970 |
|
---|
1971 | See to L<Transition ways from 1.xx to 2.xx.>
|
---|
1972 |
|
---|
1973 | =over
|
---|
1974 |
|
---|
1975 | =item jsonToObj and objToJson are obsoleted.
|
---|
1976 |
|
---|
1977 | Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
|
---|
1978 | (but not yet deleted from the source).
|
---|
1979 | If you use these functions in your code, please replace them
|
---|
1980 | with C<from_json> and C<to_json>.
|
---|
1981 |
|
---|
1982 |
|
---|
1983 | =item Global variables are no longer available.
|
---|
1984 |
|
---|
1985 | C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
|
---|
1986 | - are not available any longer.
|
---|
1987 | Instead, various features can be used through object methods.
|
---|
1988 |
|
---|
1989 |
|
---|
1990 | =item Package JSON::Converter and JSON::Parser are deleted.
|
---|
1991 |
|
---|
1992 | Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
|
---|
1993 |
|
---|
1994 | =item Package JSON::NotString is deleted.
|
---|
1995 |
|
---|
1996 | There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
|
---|
1997 | and numbers. It was deleted and replaced by C<JSON::Boolean>.
|
---|
1998 |
|
---|
1999 | C<JSON::Boolean> represents C<true> and C<false>.
|
---|
2000 |
|
---|
2001 | C<JSON::Boolean> does not represent C<null>.
|
---|
2002 |
|
---|
2003 | C<JSON::null> returns C<undef>.
|
---|
2004 |
|
---|
2005 | C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
|
---|
2006 | to L<JSON::Boolean>.
|
---|
2007 |
|
---|
2008 | =item function JSON::Number is obsoleted.
|
---|
2009 |
|
---|
2010 | C<JSON::Number> is now needless because JSON::XS and JSON::PP have
|
---|
2011 | round-trip integrity.
|
---|
2012 |
|
---|
2013 | =item JSONRPC modules are deleted.
|
---|
2014 |
|
---|
2015 | Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
|
---|
2016 | and C<Apache::JSONRPC > are deleted in this distribution.
|
---|
2017 | Instead 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 |
|
---|
2023 | You should set C<suport_by_pp> mode firstly, because
|
---|
2024 | it 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 |
|
---|
2043 | equivalent 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 |
|
---|
2054 | equivalent 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 |
|
---|
2069 | The C<new> method in 2.x takes any parameters no longer.
|
---|
2070 | You can set parameters instead;
|
---|
2071 |
|
---|
2072 | $json = JSON->new->pretty;
|
---|
2073 |
|
---|
2074 | =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
|
---|
2075 |
|
---|
2076 | If C<indent> is enable, that menas C<$JSON::Pretty> flag set. And
|
---|
2077 | C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
|
---|
2078 | In conclusion:
|
---|
2079 |
|
---|
2080 | $json->indent->space_before->space_after;
|
---|
2081 |
|
---|
2082 | Equivalent to:
|
---|
2083 |
|
---|
2084 | $json->pretty;
|
---|
2085 |
|
---|
2086 | To 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 |
|
---|
2100 | use 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 |
|
---|
2110 | Disable. 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 |
|
---|
2116 | This is the ascii sort.
|
---|
2117 |
|
---|
2118 | If 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 |
|
---|
2126 | Can'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 |
|
---|
2134 | Needless. C<JSON> backend modules have the round-trip integrity.
|
---|
2135 |
|
---|
2136 | =item $JSON::UTF8
|
---|
2137 |
|
---|
2138 | Needless because C<JSON> (JSON::XS/JSON::PP) sets
|
---|
2139 | the 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 |
|
---|
2161 | See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
|
---|
2162 |
|
---|
2163 | =item $JSON::UnMapping
|
---|
2164 |
|
---|
2165 | Disable. See to L<MAPPING>.
|
---|
2166 |
|
---|
2167 | =item $JSON::SelfConvert
|
---|
2168 |
|
---|
2169 | This option was deleted.
|
---|
2170 | Instead of it, if a givien blessed object has the C<TO_JSON> method,
|
---|
2171 | C<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 |
|
---|
2176 | Note 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 |
|
---|
2190 | No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
|
---|
2191 |
|
---|
2192 |
|
---|
2193 | =head1 BUGS
|
---|
2194 |
|
---|
2195 | Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
|
---|
2196 |
|
---|
2197 |
|
---|
2198 | =head1 SEE ALSO
|
---|
2199 |
|
---|
2200 | Most of the document is copied and modified from JSON::XS doc.
|
---|
2201 |
|
---|
2202 | L<JSON::XS>, L<JSON::PP>
|
---|
2203 |
|
---|
2204 | C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
|
---|
2205 |
|
---|
2206 | =head1 AUTHOR
|
---|
2207 |
|
---|
2208 | Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
|
---|
2209 |
|
---|
2210 | JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
|
---|
2211 |
|
---|
2212 | The relese of this new version owes to the courtesy of Marc Lehmann.
|
---|
2213 |
|
---|
2214 |
|
---|
2215 | =head1 COPYRIGHT AND LICENSE
|
---|
2216 |
|
---|
2217 | Copyright 2005-2010 by Makamaka Hannyaharamitu
|
---|
2218 |
|
---|
2219 | This library is free software; you can redistribute it and/or modify
|
---|
2220 | it under the same terms as Perl itself.
|
---|
2221 |
|
---|
2222 | =cut
|
---|
2223 |
|
---|