Subversion Repositories DevTools

Rev

Rev 4384 | Details | Compare with Previous | Last modification | View Log | RSS feed

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