=encoding UTF-8 =head1 NAME JSON::Create - Create JSON =head1 SYNOPSIS use JSON::Create 'create_json'; my %hash = (a => 'b', c => 'd'); print create_json (\%hash); produces output {"c":"d","a":"b"} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/synopsis.pl> in the distribution.) =head1 VERSION This document describes JSON::Create version 0.35, corresponding to L at Fri Jul 16 07:42:12 2021 +0900. =head1 DESCRIPTION JSON::Create encodes Perl variables into JSON. The basic routine L gives common defaults. The stricter version L accepts only unambiguous inputs. For more customization, an object created with L and run with L allows specifying behaviour in more detail. JSON::Create handles no string encoding except UTF-8. It supports serialization of objects via user-defined callbacks. Its companion module L parses JSON into Perl. Errors in processing result in a warning and an undefined return value. This behaviour can be altered with the method L. =head1 FUNCTIONS =head2 create_json my $json = create_json (\%hash, %args); This converts a hash reference, array reference, or scalar into JSON. The return value is the output JSON as a string. The arguments available in C<%args> are the same as L and L. Details of the conversion of each type are given in L. =head2 create_json_strict my $json = create_json_strict (\%hash, %args); This is the same as L, except that it rejects ambiguous inputs. See L for details. It is effectively identical to my $json = create_json (\%hash, %args, strict => 1); The "strict" option can be set in C<%args> without producing an error, but it will be overridden. This function was added in version 0.20 of the module. =head2 write_json write_json ('file.json', \%hash, %options); Write the contents of C<%hash> (or an array reference or scalar) to the file specified in the first argument. This takes all the same arguments as L, L and L. This function was added in version 0.30 of the module. =head1 METHODS If you need to alter the format of the output from the defaults of L or L, create an object with L and then set preferences on that object before producing output with L. =head2 create my $json = $jc->create ($input); This does exactly the same thing as L, unless the output format associated with C<$jc> has been altered using L. The return value is the output JSON. =head2 fatal_errors $jc->fatal_errors (1); If this is called with a true value, errors in the input are upgraded from warnings to fatal errors. use JSON::Create; my $jc = JSON::Create->new (); $jc->fatal_errors (1); my $invalid_utf8 = "\x{99}\x{ff}\x{88}"; eval { $jc->run ($invalid_utf8); }; if ($@) { print "Fatal error: $@\n"; } produces output Fatal error: Invalid UTF-8 at /usr/home/ben/projects/json-create/examples/fatal-errors.pl line 9. (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/fatal-errors.pl> in the distribution.) This method was added in version 0.10 of the module. =head2 new my $jc = JSON::Create->new (); Create a new "JSON::Create" object. Use L to generate JSON with it. It is possible to supply arguments with new: my $jc = JSON::Create->new (%args); All of the same values as L may be used. =head2 set $json->set (strict => 1, fatal_errors => 1, validate => 1); =over =item downgrade_utf8 option This corresponds to L. =item escape_slash option This corresponds to L. =item fatal_errors option This corresponds to L. =item indent option This corresponds to L. =item no_javascript_safe option This corresponds to L. =item non_finite_handler option This corresponds to L. =item object_handler option This corresponds to L. =item replace_bad_utf8 option This corresponds to L. =item sort option This corresponds to L. =item strict option This corresponds to L. =item type_handler option This corresponds to L. =item unicode_escape_all option This corresponds to L. =item unicode_upper option This corresponds to L. =item validate option This corresponds to L. =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 (character strings), =item * non-finite floating point numbers (NaN or infinite values), and =item * scalar references. =back Calling L with such inputs results in a return value of C (the undefined value) and a warning being printed. You can override the behaviour for objects with L, L, for non-data types and scalar references with L, and for non-finite numbers with L. The rejection of non-ASCII bytes in non-C strings cannot be overridden, so users need to ensure that all input is either ASCII-only or character string-only (C). 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 to format the output JSON in a different way from the default when operating L. These methods do not affect the behaviour of L or L. =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 or C 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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/boolean.pl> in the distribution.) If you prefer to take over all object handling yourself, there is also L, which overrides what is set with C. =head3 Interoperability The boolean values of the following Perl modules can interoperate with JSON::Create. =over =item L $jc->bool ('boolean'); =item L $jc->bool ('JSON::Tiny::_Bool'); Round trip compatibility is also confirmed for JSON::Tiny version 0.54. =item L $jc->bool ('JSON::PP::Boolean'); Round trip compatibility is also confirmed for JSON::PP version 2.27300. =item L $jc->bool ('JSON::PP::Boolean'); B the above is not a typo, L is the correct object type for Types::Serialiser. To confirm this, try print ref $Types::Serialiser::false; =item L $jc->bool ('JSON::PP::Boolean', 'Mojo::JSON::_Bool'); Round trip compatibility is also confirmed for Mojo::JSON version 8.65. The current version of Mojo::JSON (Mojolicious version 8.65) uses C for true and false values. Older versions used their own type, C. JSON::Create's compatibility tests for Mojo::JSON compatibility are available only in the git repository as F, rather than in the CPAN release, because different versions of Mojolicious differ a lot in not only function names but also variable names, as seen above. =back You can handle multiple modules with the same object: $jc->bool (qw/boolean JSON::Tiny::_Bool JSON::PP::Boolean/); The compatibility of the above modules can be confirmed by running the test script F in the distribution. However, JSON::Create does not install these modules, so unless you have installed them yourself, the tests will just be skipped. More modules will be added to this list as time permits. =head2 cmp Set a user-defined routine to be used with the L option. Sorting the keys of objects in a user-defined order will reduce the performance of the module. The built-in variables C<$a> and C<$b> are not available to your sort routine, so you need to get the arguments yourself. =head3 Sorting object elements case-independently use utf8; use FindBin '$Bin'; use JSON::Create; my $jc = JSON::Create->new (sort => 1, indent => 1); $jc->cmp (\&uccmp); my %emojis = ( lifeforms => { Kingkong => '🦍', goat => '🐐', elephant => '🐘', Grape => 'πŸ‡', Watermelon => 'πŸ‰', melon => '🍈', # What if life exists based on another element? πŸ–– siliconbased => '❄', }, ); print $jc->run (\%emojis); sub uccmp { my ($a, $b) = @_; return uc ($a) cmp uc ($b); } produces output { "lifeforms":{ "elephant":"🐘", "goat":"🐐", "Grape":"πŸ‡", "Kingkong":"🦍", "melon":"🍈", "siliconbased":"❄", "Watermelon":"πŸ‰" } } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/cmp.pl> in the distribution.) This method was added in version 0.29 of the module. =head2 downgrade_utf8 $jc->downgrade_utf8 (1); If this is set to a true value, the return value of L or L is never upgraded to character strings, or C. This overrides the default behaviour, which is to upgrade the output to C if any part of the input is C, or if the user has requested replacement with L and there are bad characters in the user's input. See L for details. All output of JSON::Create is valid UTF-8, regardless of what this flag is set to. See L. This method was added in version 0.18 of the module. =head2 escape_slash $jc->escape_slash (1); Call this with a true value to make the slash (known as the "solidus" in the JSON specification) be escaped with a backslash, so C gets turned into C<\/>. Call this with any false value to make the slash not be escaped (the default behaviour). =head3 Escaping slashes use JSON::Create; my $jc = JSON::Create->new (); my $in = {'/dog/' => '/run/'}; print $jc->run ($in), "\n"; $jc->escape_slash (1); print $jc->run ($in), "\n"; $jc->escape_slash (0); print $jc->run ($in), "\n"; produces output {"/dog/":"/run/"} {"\/dog\/":"\/run\/"} {"/dog/":"/run/"} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/escape-slash.pl> in the distribution.) See also L. This method was added in version 0.07 of the module. =head2 indent $jc->indent (1); Add whitespace indentation to the output. The formula applied is to add a newline plus indentation after each opening bracket, add the same after each comma, and add the same before each closing bracket. Tabs are used for all indentation. The number of tabs is decided by the number of brackets open. =head3 Example of indentation use JSON::Create; my %thing = ("it's your thing" => [qw! do what you !, {wanna => 'do'}], "I can't tell you" => [{who => 2}, qw! sock it!, 2]); my $jc = JSON::Create->new (); $jc->indent (1); print $jc->run (\%thing); produces output { "it's your thing":[ "do", "what", "you", { "wanna":"do" } ], "I can't tell you":[ { "who":2 }, "sock", "it", 2 ] } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/indent.pl> in the distribution.) =head3 Reformatting the indentation Users who prefer a different style of indentation should easily be able to modify this output to their needs using simple substitutions, for example C will convert from tabs to two space indentation. use JSON::Create; my %thing = ("it's your thing" => [qw! do what you !, {wanna => 'do'}], "I can't tell you" => [{who => 2}, qw! sock it!, 2]); my $jc = JSON::Create->new (); $jc->indent (1); my $out = $jc->run (\%thing); $out =~ s/^(\t+)/ " " x length ($1) /gesm; print $out; produces output { "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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/js-safe.pl> in the distribution.) See also L. =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. The routine C 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 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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/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 callback, use a closure. See the discussion at L for an example. =item * Returning undef halts processing If your handler returns the undefined value, L prints a warning L, 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. If you do not use this, and your return value happens to contain invalid UTF-8, you may see the error L. Please see L for more about this error. =item * Exception handling Exceptions (C) thrown within C callbacks are not caught by L but passed through to the parent. Please see the discussion at L for an example. =back This method was added in version 0.17 of the module. =head2 obj $jc->obj ('Zilog::Z80' => sub { my ($obj) = @_; print "\"Z80\""; }); Register JSON generators for Perl objects. When JSON::Create finds an object with a registered type, it will call the method you have supplied. The argument to C is a hash. The keys are object names, and the corresponding values are code references to the JSON serializer for that object: $jc->obj ( 'My::Object' => \& object_to_json, ); The output is passed through to the output string unaltered. To have your JSON output checked for validity, use the L option. The function is called with the object reference as its only argument, as if called like this: my $user_json = $my_object->object_to_json (); The return value of the function, C in the above example, must be a single value, a string containing the object's JSON encoding. use JSON::Create; my $jc = JSON::Create->new (); package Zilog::Z80; sub new { return bless { memory => '64 kbytes' }; } sub to_json { my ($self) = @_; return '"I can address as many as '.$self->{memory}.' of memory"'; } 1; package main; my $zilog = Zilog::Z80->new (); my %stuff = (zilog => $zilog); print $jc->run (\%stuff), "\n"; # Set up our object's method for printing JSON. $jc->obj ( 'Zilog::Z80' => \& Zilog::Z80::to_json, ); print $jc->run (\%stuff), "\n"; produces output {"zilog":{"memory":"64 kbytes"}} {"zilog":"I can address as many as 64 kbytes of memory"} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/zilog.pl> in the distribution.) The function is called "in scalar context", so use JSON::Create; my $jc = JSON::Create->new (); $jc->validate (1); $jc->type_handler (sub { return ('"a"', '"b"', '"c"'); }); print $jc->run ({ x => *STDOUT }); produces output {"x":"c"} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/too-many-values.pl> in the distribution.) If you need to pass or return more than a single argument, use a closure: use JSON::Create; package My::Cool::Object; sub new { return bless {}; } sub serialize { return ('true', 'false'); }; 1; package main; my $object = My::Cool::Object->new (); my $jc = JSON::Create->new (); my ($arg1, $arg2); $jc->obj ( 'My::Cool::Object' => sub { my ($obj) = @_; my ($value1, $value2) = My::Cool::Object::serialize ($obj, $arg1, $arg2); return $value2; }, ); print $jc->run ({cool => $object}); produces output {"cool":false} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/closure.pl> in the distribution.) =head3 Throwing an exception in your callback Exceptions (fatal errors) are not caught by JSON::Create, so if you want to halt the execution of JSON::Create, you can throw an exception within your callback. use JSON::Create; package Funky::Monkey::Baby; sub new {return bless {};} 1; package main; my $jc = JSON::Create->new (); $jc->obj ( 'Funky::Monkey::Baby' => sub { die "There is no such thing as a funky monkey baby"; }, ); eval { $jc->run ({fmb => Funky::Monkey::Baby->new ()}); }; if ($@) { print "$@\n"; } produces output There is no such thing as a funky monkey baby at /usr/home/ben/projects/json-create/examples/exception.pl line 10. (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/exception.pl> in the distribution.) If you prefer to take over all object handling yourself, there is also L. If your handler returns the undefined value, L prints a warning L, halts further processing of the input, and returns the undefined value. =head2 obj_handler $jc->obj_handler (\& my_obj_handler); Supply an object handler. If you supply this, all objects will be handled by your handler. For example, you can replace all objects with 'null' or die if an object is found. =over =item * Calling convention The obj_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->{obj_handler}} ($item); To pass or return multiple values via the C callback, use a closure. See the discussion at L for an example. =item * Returning undef halts processing If your handler returns the undefined value, L prints a warning L, 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->obj_handler (); or with a false argument: $jc->obj_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. If you do not use this, and your return value happens to contain invalid UTF-8, you may see the error L. Please see L for more about this error. =item * Exception handling Exceptions (C) thrown within C callbacks are not caught by L but passed through to the parent. Please see the discussion at L for an example. =back =head3 Turning various types of object into JSON Here is an example of handling various types of object with a user-supplied handler: use utf8; use FindBin '$Bin'; use JSON::Create; package Monkey::Shines; sub new { return bless {}; } 1; package Monkey::Shines::Bool; sub true { my $monkey = 1; return bless \$monkey; } sub false { my $monkey = 0; return bless \$monkey; } 1; package main; my $monkeys = { CuriousGeorge => Monkey::Shines->new (), KingKong => Monkey::Shines::Bool->true (), FunkyKong => Monkey::Shines::Bool->false (), PeterTork => "Monkees", }; my $obj_handler = sub { my ($obj) = @_; if (ref ($obj) =~ /bool/i) { return $$obj ? 'true' : 'false'; } else { return 'null'; } }; my $jc = JSON::Create->new (indent => 1, sort => 1); print $jc->run ($monkeys), "\n"; $jc->obj_handler ($obj_handler); print $jc->run ($monkeys), "\n"; $jc->obj_handler (); print $jc->run ($monkeys), "\n"; produces output { "CuriousGeorge":{}, "FunkyKong":0, "KingKong":1, "PeterTork":"Monkees" } { "CuriousGeorge":null, "FunkyKong":false, "KingKong":true, "PeterTork":"Monkees" } { "CuriousGeorge":{}, "FunkyKong":0, "KingKong":1, "PeterTork":"Monkees" } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/obj-handler.pl> in the distribution.) =head3 Turning everything into JSON Here is an example of a "try harder" routine which does something like the L module does, by looking for methods on all objects: use utf8; use FindBin '$Bin'; use JSON::Create 'create_json'; use Mojo::URL; use Path::Tiny; sub try_harder { my ($obj) = @_; my $type = ref $obj; if ($obj->can ('TO_JSON')) { print "Jsonifying $type with 'TO_JSON'.\n"; return create_json ($obj->TO_JSON ()); } elsif ($obj->can ('to_string')) { print "Stringifying $type with 'to_string'.\n"; # The call to "create_json" makes sure that the string is # valid as a JSON string. return create_json ($obj->to_string ()); } else { return create_json ($obj); } } my $jc = JSON::Create->new (indent => 1, sort => 1, validate => 1); $jc->obj_handler (\& try_harder); print $jc->run ({ url => Mojo::URL->new('http://sri:foo@example.com:3000/foo?foo=bar#23'), path => path ('/home/ben/software/install/bin/perl'), }), "\n"; produces output Jsonifying Path::Tiny with 'TO_JSON'. Stringifying Mojo::URL with 'to_string'. { "path":"/home/ben/software/install/bin/perl", "url":"http://example.com:3000/foo?foo=bar#23" } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/try-harder.pl> in the distribution.) This C overrides whatever you have set with L or L. Currently, it does not print a warning about this. See L. The routine you use to handle objects may be the same as the routine you use to handle types. See L. For more details about the callbacks, see L. This method was added in version 0.13 of the module. =head2 replace_bad_utf8 $jc->replace_bad_utf8 (1); Replace invalid UTF-8 in the inputs with the Unicode replacement character U+FFFD, rather than produce the warning or error L. If C is used on input containing only strings not marked as character strings, and bad UTF-8 is found, JSON::Create marks the output as a character string. Otherwise the replacement character itself is just a series of broken bytes. This behaviour can be altered with the method L. This method was added in version 0.12 of the module. =head2 set_fformat $jc->set_fformat ('%e'); This sets the printf-style format string used to print floating point numbers. This is validated and a warning printed if the format cannot be used. The format is also restricted to a maximum length to prevent buffer overflows within the module. =head3 Setting the format of floating point numbers use JSON::Create; my $jc = JSON::Create->new (); my @array = (1000000000.0,3.141592653589793238462643383279502884197169399375105820974944592307816406,0.000000001); print $jc->run (\@array), "\n"; $jc->set_fformat ('%.3f'); print $jc->run (\@array), "\n"; $jc->set_fformat ('%E'); print $jc->run (\@array), "\n"; $jc->set_fformat (); print $jc->run (\@array), "\n"; produces output [1e+09,3.14159,1e-09] [1000000000.000,3.142,0.000] [1.000000E+09,3.141593E+00,1.000000E-09] [1e+09,3.14159,1e-09] (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/set-fformat.pl> in the distribution.) This method was added in version 0.07 of the module. =head2 sort $jc->sort (1); Sort hash keys. The default is to use Perl's string sorting. Use L to supply your own sorting routine. This does not affect the order of array elements, only hash keys. =head3 JSON with indentation and sorted keys use utf8; use JSON::Create; my %emojis = ( animals => { kingkong => '🦍', goat => '🐐', elephant => '🐘', }, fruit => { grape => 'πŸ‡', watermelon => 'πŸ‰', melon => '🍈', }, baka => { # Japanese words 'ば' => 'か', 'あ' => 'ほ', 'ま' => 'ぬけ', }, ); my $jc = JSON::Create->new (); my @moons = qw!πŸŒ‘ πŸŒ’ πŸŒ“ πŸŒ” πŸŒ• πŸŒ– πŸŒ— 🌘!; my $i = 0; for (@moons) { $emojis{moons}{$_} = $i; $i++; } $jc->sort (1); $jc->indent (1); print $jc->run (\%emojis); produces output { "animals":{ "elephant":"🐘", "goat":"🐐", "kingkong":"🦍" }, "baka":{ "あ":"ほ", "ば":"か", "ま":"ぬけ" }, "fruit":{ "grape":"πŸ‡", "melon":"🍈", "watermelon":"πŸ‰" }, "moons":{ "πŸŒ‘":0, "πŸŒ’":1, "πŸŒ“":2, "πŸŒ”":3, "πŸŒ•":4, "πŸŒ–":5, "πŸŒ—":6, "🌘":7 } } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/sort.pl> in the distribution.) This method was added in version 0.29 of the module. =head2 type_handler $jc->type_handler (sub {return 'null'}); By default, when JSON::Create encounters a variable of a type which it doesn't know what to do with, such as a glob or code reference, it prints a warning and returns an undefined value. See L. The method C sets up a callback which is called when a variable of an unhandled type is found in the input. For example, to put the JSON literal C in the output when a reference to a variable of an unhandled type is encountered, rather than print an error, the above example will do it. =over =item * Calling convention The type_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->{type_handler}} ($item); To pass or return multiple values via the C callback, use a closure. See the discussion at L for an example. =item * Returning undef halts processing If your handler returns the undefined value, L prints a warning L, 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->type_handler (); or with a false argument: $jc->type_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. If you do not use this, and your return value happens to contain invalid UTF-8, you may see the error L. Please see L for more about this error. =item * Exception handling Exceptions (C) thrown within C callbacks are not caught by L but passed through to the parent. Please see the discussion at L for an example. =back =head3 Ways to handle types The following example shows a few possibilities for handling types: use utf8; use FindBin '$Bin'; use JSON::Create 'create_json'; my %crazyhash = ( 'code' => sub { return "κ°•λ‚¨μŠ€νƒ€μΌ"; }, 'regex' => qr/.*/, 'glob' => *STDOUT, ); # Let's validate the output of the subroutine below. my $jc = JSON::Create->new (validate => 1, indent => 1, sort => 1); # Try this one weird old trick to convert your Perl type. $jc->type_handler ( sub { my ($thing) = @_; my $value; my $type = ref ($thing); if ($type eq 'CODE') { $value = &$thing; } else { $value = "$thing"; } return create_json ({ type => $type, value => $value, }, indent => 1, sort => 1); } ); print $jc->run (\%crazyhash), "\n"; produces output { "code":{ "type":"CODE", "value":"κ°•λ‚¨μŠ€νƒ€μΌ" }, "glob":{ "type":"GLOB", "value":"GLOB(0x209a82a0)" }, "regex":{ "type":"Regexp", "value":"(?^:.*)" } } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/type-handler.pl> in the distribution.) If the L option is chosen, this method is also passed scalar references. use JSON::Create; my $jc = JSON::Create->new (); $jc->strict (1); print "Before: ", $jc->run (\1), "\n"; $jc->type_handler (sub { my ($thing) = @_; if (ref $thing eq 'SCALAR') { return $$thing; } }); print "After: ", $jc->run (\1), "\n"; produces output Input's type cannot be serialized to JSON at /usr/home/ben/projects/json-create/examples/type-handler-scalar.pl line 7. Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/type-handler-scalar.pl line 7. Before: After: 1 (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/type-handler-scalar.pl> in the distribution.) This method was added in version 0.10 of the module. =head2 unicode_escape_all $jc->unicode_escape_all (1); Call this with a true value to make all Unicode characters be escaped into the C<\u3000> format. A false value switches that off again. =head3 Escape all Unicode use JSON::Create; use utf8; my $jc = JSON::Create->new (); my $in = '血ブâ1ↂΟͺ'; print $jc->run ($in), "\n"; $jc->unicode_escape_all (1); print $jc->run ($in), "\n"; $jc->unicode_upper (1); print $jc->run ($in), "\n"; $jc->unicode_escape_all (0); print $jc->run ($in), "\n"; produces output "血ブâ1ↂΟͺ" "\u8d64\u30d6\u00f6\uff21\u2182\u03ea" "\u8D64\u30D6\u00F6\uFF21\u2182\u03EA" "血ブâ1ↂΟͺ" (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/escape-all.pl> in the distribution.) =head3 Output is always UTF-8 Note that JSON::Create contains its own UTF-8 validation, and this escaping is applied regardless of whether Perl marks the bytes as "utf8" or not: use JSON::Create; no utf8; my $jc = JSON::Create->new (); my $in = '血ブâ1ↂΟͺ'; print $jc->run ($in), "\n"; $jc->unicode_escape_all (1); print $jc->run ($in), "\n"; $jc->unicode_upper (1); print $jc->run ($in), "\n"; $jc->unicode_escape_all (0); print $jc->run ($in), "\n"; produces output "血ブâ1ↂΟͺ" "\u8d64\u30d6\u00f6\uff21\u2182\u03ea" "\u8D64\u30D6\u00F6\uFF21\u2182\u03EA" "血ブâ1ↂΟͺ" (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/escape-all-no-utf8.pl> in the distribution.) See also L. =head2 unicode_upper $jc->unicode_upper (1); Call this with a true value to make Unicode escapes use upper case letters in the hexadecimal. See the example under L. =head2 validate $jc->validate (1); If this is called with a true value, JSON::Create validates the user-generated JSON given by the callbacks registered with L, L, L and L. The validation is done via the routine C of L, so that module must be installed, otherwise the call to C will fail. This also validates that the return value contains only valid UTF-8. If JSON::Parse is installed, and the JSON fails to validate, a warning will be produced containing the invalid JSON string and the error produced by C, and the return value will be undefined. This method was added in version 0.07 of the module. =head1 CONVERSIONS This section details what conversions are applied to the various inputs to produce outputs. =head2 Hashes JSON::Create turns associative arrays into JSON objects. The keys are written into JSON as strings, with control characters escaped. The order of the keys is as they are supplied by Perl. use JSON::Create 'create_json'; my %example = ( x => 1, y => 2, z => 3, ); print create_json (\%example); produces output {"y":2,"x":1,"z":3} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/hash.pl> in the distribution.) Nested hashes are recursively followed: use JSON::Create 'create_json'; my %example = ( x => { y => 2, z => 3, }, a => { b => 4, c => 5, }, ); print create_json (\%example); produces output {"x":{"z":3,"y":2},"a":{"b":4,"c":5}} (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/nested-hash.pl> in the distribution.) =head2 Arrays Arrays are converted to JSON arrays. The order of elements of the array is left unchanged. use JSON::Create 'create_json'; my @array = (1, 2, 2.5, qw/mocha dusty milky/, qw/Tico Rocky Pinky/); print create_json (\@array); produces output [1,2,2.5,"mocha","dusty","milky","Tico","Rocky","Pinky"] (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/array.pl> in the distribution.) Nested arrays are recursively followed: use JSON::Create 'create_json'; my @array = ([1, 2, 2.5], [qw/mocha dusty milky/], [qw/Tico Rocky Pinky/]); print create_json (\@array); produces output [[1,2,2.5],["mocha","dusty","milky"],["Tico","Rocky","Pinky"]] (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/nested-array.pl> in the distribution.) Nested hashes and arrays are converted similarly: use JSON::Create 'create_json'; my $nested = { numbers => [1, 2, 2.5, 99.99], cats => [qw/mocha dusty milky/], dogs => [qw/Tico Rocky Pinky/], fruit => { thai => 'pineapple', japan => 'persimmon', australia => 'orange', }, }; print create_json ($nested, sort => 1, indent => 1); produces output { "cats":[ "mocha", "dusty", "milky" ], "dogs":[ "Tico", "Rocky", "Pinky" ], "fruit":{ "australia":"orange", "japan":"persimmon", "thai":"pineapple" }, "numbers":[ 1, 2, 2.5, 99.99 ] } (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/nested.pl> in the distribution.) =head2 Scalars Non-reference Perl scalars are converted to JSON strings or numbers, depending on what Perl thinks they contain. =head3 Strings As far as possible, strings are written as they are to the JSON. JSON is Unicode, so all output is checked for Unicode validity. Further, this module insists on UTF-8. (See L.) Invalid UTF-8 within input strings produces the error L and the undefined value is returned. This behaviour can be altered with the method L. (For full details of the corner cases, see L.) Some whitespace and control characters must be also escaped for the output to be valid JSON. (See L.) In addition to this, L or the L option reject inputs containing non-ASCII bytes (bytes with values of from 128 to 255) which are not marked as character strings. =head4 Control characters and whitespace To form valid JSON, bytes of value less than 0x20 in a Perl string must be converted into JSON escapes, either the whitespace escapes \b (backspace) \r, \t, \n, and \f, or the form \u0001 for other control characters. Further, the backslash must be written as C<\\> and double quotes must be written as C<\">. 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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/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. 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, 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. Other Unicode values are not escaped. This behaviour can be altered with the method L. =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 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 JSON does not allow NaN or infinity as bare values. From page 6 of L: =over Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. =back L converts NaN (not a number) values to C<"nan"> (the letters C surrounded by double quotes), and positive and negative infinity to C<"inf"> and C<"-inf"> respectively. L disallows non-finite numbers. If a non-finite number appears within its input, it prints a warning L 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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/strict-non-finite.pl> in the distribution.) A JSON::Create object created with L converts in the same way as L. This behaviour can be altered with the method L. If L is specified, non-finite numbers are passed to L if it is set, and if not, it prints a warning L 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|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/undef.pl> in the distribution.) =head3 Booleans Booleans (C and C) from input via JSON::Parse version 0.37 or later will be turned into the outputs C and C: use JSON::Parse '0.38', 'parse_json'; use JSON::Create 'create_json'; my $in = parse_json ('[true,false,"boo"]'); print create_json ($in); produces output [true,false,"boo"] (This example is included as L|https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/json-parse-bool.pl> in the distribution.) Other kinds of object can be converted to booleans using the method L (see below). =head3 Context-dependent variables A context-dependent variable is a variable which may contain a string and a numerical value. Usually the string value is just a representation of the number, but it may not be. The behaviour in the case of a context-dependent variable is as follows. If the variable contains a valid numerical value, the numerical value is used in the output JSON, rather than the string value. However, some modules, like L, return context-dependent hash values which have a non-number-like string under the key C