JSON

 view release on metacpan or  search on metacpan

lib/JSON/backportPP.pm  view on Meta::CPAN


    bless $self, $class;
}


sub encode {
    return $_[0]->PP_encode_json($_[1]);
}


sub decode {
    return $_[0]->PP_decode_json($_[1], 0x00000000);
}


sub decode_prefix {
    return $_[0]->PP_decode_json($_[1], 0x00000001);
}


# accessor


# pretty printing

sub pretty {
    my ($self, $v) = @_;
    my $enable = defined $v ? $v : 1;

    if ($enable) { # indent_length(3) for JSON::XS compatibility
        $self->indent(1)->space_before(1)->space_after(1);
    }
    else {
        $self->indent(0)->space_before(0)->space_after(0);
    }

    $self;
}

# etc

sub max_depth {
    my $max  = defined $_[1] ? $_[1] : 0x80000000;
    $_[0]->{max_depth} = $max;
    $_[0];
}


sub get_max_depth { $_[0]->{max_depth}; }


sub max_size {
    my $max  = defined $_[1] ? $_[1] : 0;
    $_[0]->{max_size} = $max;
    $_[0];
}


sub get_max_size { $_[0]->{max_size}; }

sub boolean_values {
    my $self = shift;
    if (@_) {
        my ($false, $true) = @_;
        $self->{false} = $false;
        $self->{true} = $true;
        if (CORE_BOOL) {
            BEGIN { CORE_BOOL and warnings->unimport(qw(experimental::builtin)) }
            if (builtin::is_bool($true) && builtin::is_bool($false) && $true && !$false) {
                $self->{core_bools} = !!1;
            }
            else {
                delete $self->{core_bools};
            }
        }
    } else {
        delete $self->{false};
        delete $self->{true};
        delete $self->{core_bools};
    }
    return $self;
}

sub core_bools {
    my $self = shift;
    my $core_bools = defined $_[0] ? $_[0] : 1;
    if ($core_bools) {
        $self->{true} = !!1;
        $self->{false} = !!0;
        $self->{core_bools} = !!1;
    }
    else {
        $self->{true} = $JSON::PP::true;
        $self->{false} = $JSON::PP::false;
        $self->{core_bools} = !!0;
    }
    return $self;
}

sub get_core_bools {
    my $self = shift;
    return !!$self->{core_bools};
}

sub unblessed_bool {
    my $self = shift;
    return $self->core_bools(@_);
}

sub get_unblessed_bool {
    my $self = shift;
    return $self->get_core_bools(@_);
}

sub get_boolean_values {
    my $self = shift;
    if (exists $self->{true} and exists $self->{false}) {
        return @$self{qw/false true/};
    }
    return;
}

sub filter_json_object {
    if (defined $_[1] and ref $_[1] eq 'CODE') {
        $_[0]->{cb_object} = $_[1];
    } else {
        delete $_[0]->{cb_object};
    }
    $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
    $_[0];
}

sub filter_json_single_key_object {
    if (@_ == 1 or @_ > 3) {
        Carp::croak("Usage: JSON::PP::filter_json_single_key_object(self, key, callback = undef)");
    }
    if (defined $_[2] and ref $_[2] eq 'CODE') {
        $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
    } else {
        delete $_[0]->{cb_sk_object}->{$_[1]};
        delete $_[0]->{cb_sk_object} unless %{$_[0]->{cb_sk_object} || {}};
    }
    $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
    $_[0];
}

sub indent_length {
    if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
        Carp::carp "The acceptable range of indent_length() is 0 to 15.";
    }
    else {
        $_[0]->{indent_length} = $_[1];
    }
    $_[0];
}

sub get_indent_length {
    $_[0]->{indent_length};
}

sub sort_by {
    $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
    $_[0];
}

sub allow_bigint {
    Carp::carp("allow_bigint() is obsoleted. use allow_bignum() instead.");
    $_[0]->allow_bignum;
}

###############################

###
### Perl => JSON
###

lib/JSON/backportPP.pm  view on Meta::CPAN

    $enabled = $json->get_allow_blessed

See L<OBJECT SERIALISATION> for details.

If C<$enable> is true (or missing), then the C<encode> method will not
barf when it encounters a blessed reference that it cannot convert
otherwise. Instead, a JSON C<null> value is encoded instead of the object.

If C<$enable> is false (the default), then C<encode> will throw an
exception when it encounters a blessed object that it cannot convert
otherwise.

This setting has no effect on C<decode>.

=head2 convert_blessed

    $json = $json->convert_blessed([$enable])
    
    $enabled = $json->get_convert_blessed

See L<OBJECT SERIALISATION> for details.

If C<$enable> is true (or missing), then C<encode>, upon encountering a
blessed object, will check for the availability of the C<TO_JSON> method
on the object's class. If found, it will be called in scalar context and
the resulting scalar will be encoded instead of the object.

The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
returns other blessed objects, those will be handled in the same
way. C<TO_JSON> must take care of not causing an endless recursion cycle
(== crash) in this case. The name of C<TO_JSON> was chosen because other
methods called by the Perl core (== not by the user of the object) are
usually in upper case letters and to avoid collisions with any C<to_json>
function or method.

If C<$enable> is false (the default), then C<encode> will not consider
this type of conversion.

This setting has no effect on C<decode>.

=head2 allow_tags

    $json = $json->allow_tags([$enable])

    $enabled = $json->get_allow_tags

See L<OBJECT SERIALISATION> for details.

If C<$enable> is true (or missing), then C<encode>, upon encountering a
blessed object, will check for the availability of the C<FREEZE> method on
the object's class. If found, it will be used to serialise the object into
a nonstandard tagged JSON value (that JSON decoders cannot decode).

It also causes C<decode> to parse such tagged JSON values and deserialise
them via a call to the C<THAW> method.

If C<$enable> is false (the default), then C<encode> will not consider
this type of conversion, and tagged JSON values will cause a parse error
in C<decode>, as if tags were not part of the grammar.

=head2 boolean_values

    $json->boolean_values([$false, $true])

    ($false,  $true) = $json->get_boolean_values

By default, JSON booleans will be decoded as overloaded
C<$JSON::PP::false> and C<$JSON::PP::true> objects.

With this method you can specify your own boolean values for decoding -
on decode, JSON C<false> will be decoded as a copy of C<$false>, and JSON
C<true> will be decoded as C<$true> ("copy" here is the same thing as
assigning a value to another variable, i.e. C<$copy = $false>).

This is useful when you want to pass a decoded data structure directly
to other serialisers like YAML, Data::MessagePack and so on.

Note that this works only when you C<decode>. You can set incompatible
boolean objects (like L<boolean>), but when you C<encode> a data structure
with such boolean objects, you still need to enable C<convert_blessed>
(and add a C<TO_JSON> method if necessary).

Calling this method without any arguments will reset the booleans
to their default values.

C<get_boolean_values> will return both C<$false> and C<$true> values, or
the empty list when they are set to the default.

=head2 core_bools

    $json->core_bools([$enable]);

If C<$enable> is true (or missing), then C<decode>, will produce standard
perl boolean values. Equivalent to calling:

    $json->boolean_values(!!1, !!0)

C<get_core_bools> will return true if this has been set. On perl 5.36, it will
also return true if the boolean values have been set to perl's core booleans
using the C<boolean_values> method.

The methods C<unblessed_bool> and C<get_unblessed_bool> are provided as aliases
for compatibility with L<Cpanel::JSON::XS>.

=head2 filter_json_object

    $json = $json->filter_json_object([$coderef])

When C<$coderef> is specified, it will be called from C<decode> each
time it decodes a JSON object. The only argument is a reference to
the newly-created hash. If the code references returns a single scalar
(which need not be a reference), this value (or rather a copy of it) is
inserted into the deserialised data structure. If it returns an empty
list (NOTE: I<not> C<undef>, which is a valid scalar), the original
deserialised hash will be inserted. This setting can slow down decoding
considerably.

When C<$coderef> is omitted or undefined, any existing callback will
be removed and C<decode> will not change the deserialised hash in any
way.

Example, convert all JSON objects into the integer 5:

   my $js = JSON::PP->new->filter_json_object(sub { 5 });
   # returns [5]
   $js->decode('[{}]');
   # returns 5
   $js->decode('{"a":1, "b":2}');

=head2 filter_json_single_key_object

    $json = $json->filter_json_single_key_object($key [=> $coderef])

Works remotely similar to C<filter_json_object>, but is only called for
JSON objects having a single key named C<$key>.

This C<$coderef> is called before the one specified via
C<filter_json_object>, if any. It gets passed the single value in the JSON
object. If it returns a single value, it will be inserted into the data
structure. If it returns nothing (not even C<undef> but the empty list),
the callback from C<filter_json_object> will be called next, as if no
single-key callback were specified.

If C<$coderef> is omitted or undefined, the corresponding callback will be
disabled. There can only ever be one callback for a given key.

As this callback gets called less often then the C<filter_json_object>
one, decoding speed will not usually suffer as much. Therefore, single-key
objects make excellent targets to serialise Perl objects into, especially
as single-key JSON objects are as close to the type-tagged value concept
as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
support this in any way, so you need to make sure your data never looks
like a serialised Perl hash.

Typical names for the single object key are C<__class_whatever__>, or
C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
with real hashes.

Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>



( run in 1.330 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )