JSON-Create

 view release on metacpan or  search on metacpan

lib/JSON/Create.pod  view on Meta::CPAN

This corresponds to L</object_handler>.



=item replace_bad_utf8 option

This corresponds to L</replace_bad_utf8>.



=item sort option

This corresponds to L</sort>.



=item strict option

This corresponds to L</strict>.



=item type_handler option

This corresponds to L</type_handler>.



=item unicode_escape_all option

This corresponds to L</unicode_escape_all>.



=item unicode_upper option

This corresponds to L</unicode_upper>.



=item validate option

This corresponds to L</validate>.



=back

=head2 strict

    $jc->strict (1);

This switches on rejection of ambiguous inputs, which means

=over

=item * all non-data types, including objects,

=item * strings containing non-ASCII bytes (bytes with values of from 128 to 255) which are not marked as C<utf8> (character strings),

=item * non-finite floating point numbers (NaN or infinite values), and

=item * scalar references.

=back

Calling L</create> with such inputs results in a return value of C<undef>
(the undefined value) and a warning being printed. You can override
the behaviour for objects with L</obj>, L</obj_handler>, for non-data
types and scalar references with L</type_handler>, and for non-finite
numbers with L</non_finite_handler>.

The rejection of non-ASCII bytes in non-C<utf8> strings cannot be
overridden, so users need to ensure that all input is either
ASCII-only or character string-only (C<utf8>).

This method was added in version 0.20 of the module.

=head1 Methods for formatting the output

These methods work on the object created with L</new> to format the
output JSON in a different way from the default when operating
L</create>. 

These methods do not affect the behaviour of L</create_json> or
L</create_json_strict>.

=head2 bool

    $jc->bool ('boolean');
    $jc->bool (qw/boolean JSON::Tiny::_Bool/);

Given a list of names of object types, the JSON::Create object, C<$jc>
in the example, will convert objects of these types into the JSON
literals C<true> or C<false> depending on whether Perl thinks they're
true or false.

=head3 Converting booleans to "true" and "false"

    
    use JSON::Create;
    use boolean;
    my $thing = {'Yes' => true, 'No' => false};
    my $jc = JSON::Create->new ();
    print $jc->run ($thing), "\n";
    $jc->bool ('boolean');
    print $jc->run ($thing), "\n";
    


produces output

    {"Yes":1,"No":0}
    {"Yes":true,"No":false}


(This example is included as L<F<examples/boolean.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/boolean.pl> in the distribution.)


If you prefer to take over all object handling yourself, there is also
L</obj_handler>, which overrides what is set with C<bool>.

lib/JSON/Create.pod  view on Meta::CPAN

    {
      "I can't tell you":[
        {
          "who":2
        },
        "sock",
        "it",
        2
      ],
      "it's your thing":[
        "do",
        "what",
        "you",
        {
          "wanna":"do"
        }
      ]
    }


(This example is included as L<F<examples/indent-format.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/indent-format.pl> in the distribution.)


This method was added in version 0.27 of the module.

=head2 no_javascript_safe

    $jc->no_javascript_safe (1);

If called with a true value, this switches off JavaScript protection
in the output JSON. If called with a false value, the JavaScript
protection is switched on again.

=head3 Switching JavaScript-safety on and off

    use JSON::Create;
    my $in = ["\x{2028}"];
    my $jc = JSON::Create->new ();
    print $jc->run ($in), "\n";
    $jc->no_javascript_safe (1);
    print $jc->run ($in), "\n";
    


produces output

    ["\u2028"]
    ["
"]


(This example is included as L<F<examples/js-safe.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/js-safe.pl> in the distribution.)


See also L</U+2028 and U+2029 (JavaScript clashes)>.

=head2 non_finite_handler

   $jc->non_finite_handler (\& handler);

This overrides the default behaviour for handling non-finite floating
point numbers, in other words NaN (not a number) and negative or
positive infinity, with a user-defined routine. The default behaviour
of this module is described at L</Floating point numbers>. 

The routine C<handler> is supplied with the non-finite number as its
sole argument, and returns one argument, the output JSON. 

=head3 Using null for infinity and NaN

To always use C<null> in place of the default, supply a function like
the following:

    
    use JSON::Create;
    my $bread = { 'curry' => -sin(9**9**9) };
    my $jcnfh = JSON::Create->new ();
    print $jcnfh->run ($bread), "\n";
    $jcnfh->non_finite_handler(sub { return 'null'; });
    print $jcnfh->run ($bread), "\n";


produces output

    {"curry":"nan"}
    {"curry":null}


(This example is included as L<F<examples/non-finite-handler.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/non-finite-handler.pl> in the distribution.)


=over

=item * Calling convention

The non_finite_handler routine is passed a single argument and is expected
to return a single argument, the JSON to output. It is called in
scalar context. In other words, the call looks like the following:

     $json = &{$jc->{non_finite_handler}} ($item);

To pass or return multiple values via the C<non_finite_handler> callback,
use a closure. See the discussion at L</obj> for an example.

=item * Returning undef halts processing


If your handler returns the undefined value, L</create> prints a warning
L</Undefined value from user routine>, halts further processing of the
input, and returns the undefined value.


=item * Delete the handler with any false value

To remove the handler, simply call the function without an argument,

    $jc->non_finite_handler ();

or with a false argument:

    $jc->non_finite_handler (0);

The behaviour then reverts to the default.

=item * Checking the output JSON

The JSON output by your handler may be checked for validity by
switching on validation using L</validate>. If you do not use this,
and your return value happens to contain invalid UTF-8, you may see

lib/JSON/Create.pod  view on Meta::CPAN

This example demonstrates some of the necessary escaping:

    
    use JSON::Create 'create_json';
    # An example string containing various things.
    my $weirdstring = {weird => "\t\r\n\x00 " . '"' . '\\' . '/' };
    print create_json ($weirdstring);
    


produces output

    {"weird":"\t\r\n\u0000 \"\\/"}

(This example is included as L<F<examples/weirdstring.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/weirdstring.pl> in the distribution.)


=head4 U+2028 and U+2029 (JavaScript clashes)

    my $out = create_json (["\x{2028}"]);
    # $out = '["\u2028"]'

Although it is not required by the JSON standard, JSON::Create by
default escapes Unicode code points U+2028 and U+2029 as C<\u2028> and
C<\u2029> for JavaScript compatibility. This behaviour can be altered with the method L</no_javascript_safe>.

This escaping is necessary for JavaScript because of a clash between
the JSON standard and the JavaScript (ECMAScript) standard. The
characters U+2028 ("LINE SEPARATOR" in the Unicode standard) and
U+2029 ("PARAGRAPH SEPARATOR" in the Unicode standard) are valid
within JSON, as defined by L</RFC 8259>, but invalid within JavaScript
strings, as defined by the ECMA standard (See ECMA Standard ECMA-262,
"ECMAScript Language Specification", 3rd Edition, section 7.3 "Line
Terminators").

=head4 Other escapes

The forward slash, /, known as "solidus" in the JSON specification,
does not have to be escaped, and JSON::Create's default is not to
escape it. This behaviour can be altered with the method L</escape_slash>.

Other Unicode values are not escaped.  This behaviour can be altered with the method L</unicode_escape_all>.

=head3 Integers

Integers are printed in the usual way. Perl may interpret an integer
with a very large absolute value to be a floating point number, and
this module will print it out as such. See also L</Context-dependent
variables> for the handling of variables with both string and integer
values.

=head3 Floating point numbers

Finite floating point numbers are printed using printf formatting via
C<"%g">, like

    printf ("%g", $number);

This behaviour can be altered with the method L</set_fformat>

JSON does not allow NaN or infinity as bare values. From page 6 of
L</RFC 8259>:

=over

Numeric values that cannot be represented in the grammar below (such
as Infinity and NaN) are not permitted.

=back

L</create_json> converts NaN (not a number) values to
C<"nan"> (the letters C<nan> surrounded by double quotes), and
positive and negative infinity to C<"inf"> and C<"-inf">
respectively.

L</create_json_strict> disallows non-finite numbers. If a non-finite
number appears within its input, it prints a warning L</Non-finite
number in input> and returns the undefined value:

    
    use JSON::Create 'create_json_strict';
    print create_json_strict (9**9**9);
    


produces output

    Non-finite number in input at /usr/home/ben/projects/json-create/blib/lib/JSON/Create.pm line 200.
    Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/strict-non-finite.pl line 5.


(This example is included as L<F<examples/strict-non-finite.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/strict-non-finite.pl> in the distribution.)


A JSON::Create object created with L</new> converts in the same way as
L</create_json>.  This behaviour can be altered with the method L</non_finite_handler>. If L</strict> is
specified, non-finite numbers are passed to L</non_finite_handler> if
it is set, and if not, it prints a warning L</Non-finite number in
input> and returns the undefined value.

=head3 The undefined value

Undefined values in the input are mapped to the JSON literal "null".

    
    use JSON::Create 'create_json';
    print create_json ({a => undef, b => [undef, undef]}), "\n";
    


produces output

    {"a":null,"b":[null,null]}


(This example is included as L<F<examples/undef.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.36/examples/undef.pl> in the distribution.)


=head3 Booleans

Booleans (C<true> and C<false>) from input via JSON::Parse version
0.37 or later will be turned into the outputs C<true> and
C<false>:

    
    use JSON::Parse '0.38', 'parse_json';
    use JSON::Create 'create_json';
    my $in = parse_json ('[true,false,"boo"]');
    print create_json ($in);




( run in 0.712 second using v1.01-cache-2.11-cpan-39bf76dae61 )