1JSON::Create(3) User Contributed Perl Documentation JSON::Create(3)
2
3
4
6 JSON::Create - Create JSON
7
9 use JSON::Create 'create_json';
10 my %hash = (a => 'b', c => 'd');
11 print create_json (\%hash);
12
13 produces output
14
15 {"c":"d","a":"b"}
16
17 (This example is included as examples/synopsis.pl
18 <https://fastapi.metacpan.org/source/BKB/JSON-
19 Create-0.35/examples/synopsis.pl> in the distribution.)
20
22 This document describes JSON::Create version 0.35, corresponding to git
23 commit ffe5ce4b3304dac8f668133563a276f831966bbe
24 <https://github.com/benkasminbullock/json-
25 create/commit/ffe5ce4b3304dac8f668133563a276f831966bbe> at Fri Jul 16
26 07:42:12 2021 +0900.
27
29 JSON::Create encodes Perl variables into JSON. The basic routine
30 "create_json" gives common defaults. The stricter version
31 "create_json_strict" accepts only unambiguous inputs. For more
32 customization, an object created with "new" and run with "create"
33 allows specifying behaviour in more detail.
34
35 JSON::Create handles no string encoding except UTF-8. It supports
36 serialization of objects via user-defined callbacks. Its companion
37 module JSON::Parse parses JSON into Perl.
38
39 Errors in processing result in a warning and an undefined return value.
40 This behaviour can be altered with the method "fatal_errors".
41
43 create_json
44 my $json = create_json (\%hash, %args);
45
46 This converts a hash reference, array reference, or scalar into JSON.
47 The return value is the output JSON as a string. The arguments
48 available in %args are the same as "new" and "set".
49
50 Details of the conversion of each type are given in "CONVERSIONS".
51
52 create_json_strict
53 my $json = create_json_strict (\%hash, %args);
54
55 This is the same as "create_json", except that it rejects ambiguous
56 inputs. See "strict" for details. It is effectively identical to
57
58 my $json = create_json (\%hash, %args, strict => 1);
59
60 The "strict" option can be set in %args without producing an error, but
61 it will be overridden.
62
63 This function was added in version 0.20 of the module.
64
65 write_json
66 write_json ('file.json', \%hash, %options);
67
68 Write the contents of %hash (or an array reference or scalar) to the
69 file specified in the first argument. This takes all the same arguments
70 as "create_json", "new" and "set".
71
72 This function was added in version 0.30 of the module.
73
75 If you need to alter the format of the output from the defaults of
76 "create_json" or "create_json_strict", create an object with "new" and
77 then set preferences on that object before producing output with
78 "create".
79
80 create
81 my $json = $jc->create ($input);
82
83 This does exactly the same thing as "create_json", unless the output
84 format associated with $jc has been altered using "Methods for
85 formatting the output". The return value is the output JSON.
86
87 fatal_errors
88 $jc->fatal_errors (1);
89
90 If this is called with a true value, errors in the input are upgraded
91 from warnings to fatal errors.
92
93 use JSON::Create;
94 my $jc = JSON::Create->new ();
95 $jc->fatal_errors (1);
96 my $invalid_utf8 = "\x{99}\x{ff}\x{88}";
97 eval {
98 $jc->run ($invalid_utf8);
99 };
100 if ($@) {
101 print "Fatal error: $@\n";
102 }
103
104 produces output
105
106 Fatal error: Invalid UTF-8 at /usr/home/ben/projects/json-create/examples/fatal-errors.pl line 9.
107
108 (This example is included as examples/fatal-errors.pl
109 <https://fastapi.metacpan.org/source/BKB/JSON-
110 Create-0.35/examples/fatal-errors.pl> in the distribution.)
111
112 This method was added in version 0.10 of the module.
113
114 new
115 my $jc = JSON::Create->new ();
116
117 Create a new "JSON::Create" object. Use "create" to generate JSON with
118 it. It is possible to supply arguments with new:
119
120 my $jc = JSON::Create->new (%args);
121
122 All of the same values as "set" may be used.
123
124 set
125 $json->set (strict => 1, fatal_errors => 1, validate => 1);
126
127 downgrade_utf8 option
128 This corresponds to "downgrade_utf8".
129
130 escape_slash option
131 This corresponds to "escape_slash".
132
133 fatal_errors option
134 This corresponds to "fatal_errors".
135
136 indent option
137 This corresponds to "indent".
138
139 no_javascript_safe option
140 This corresponds to "no_javascript_safe".
141
142 non_finite_handler option
143 This corresponds to "non_finite_handler".
144
145 object_handler option
146 This corresponds to "object_handler".
147
148 replace_bad_utf8 option
149 This corresponds to "replace_bad_utf8".
150
151 sort option
152 This corresponds to "sort".
153
154 strict option
155 This corresponds to "strict".
156
157 type_handler option
158 This corresponds to "type_handler".
159
160 unicode_escape_all option
161 This corresponds to "unicode_escape_all".
162
163 unicode_upper option
164 This corresponds to "unicode_upper".
165
166 validate option
167 This corresponds to "validate".
168
169 strict
170 $jc->strict (1);
171
172 This switches on rejection of ambiguous inputs, which means
173
174 β’ all non-data types, including objects,
175
176 β’ strings containing non-ASCII bytes (bytes with values of from 128
177 to 255) which are not marked as "utf8" (character strings),
178
179 β’ non-finite floating point numbers (NaN or infinite values), and
180
181 β’ scalar references.
182
183 Calling "create" with such inputs results in a return value of "undef"
184 (the undefined value) and a warning being printed. You can override the
185 behaviour for objects with "obj", "obj_handler", for non-data types and
186 scalar references with "type_handler", and for non-finite numbers with
187 "non_finite_handler".
188
189 The rejection of non-ASCII bytes in non-"utf8" strings cannot be
190 overridden, so users need to ensure that all input is either ASCII-only
191 or character string-only ("utf8").
192
193 This method was added in version 0.20 of the module.
194
196 These methods work on the object created with "new" to format the
197 output JSON in a different way from the default when operating
198 "create".
199
200 These methods do not affect the behaviour of "create_json" or
201 "create_json_strict".
202
203 bool
204 $jc->bool ('boolean');
205 $jc->bool (qw/boolean JSON::Tiny::_Bool/);
206
207 Given a list of names of object types, the JSON::Create object, $jc in
208 the example, will convert objects of these types into the JSON literals
209 "true" or "false" depending on whether Perl thinks they're true or
210 false.
211
212 Converting booleans to "true" and "false"
213
214 use JSON::Create;
215 use boolean;
216 my $thing = {'Yes' => true, 'No' => false};
217 my $jc = JSON::Create->new ();
218 print $jc->run ($thing), "\n";
219 $jc->bool ('boolean');
220 print $jc->run ($thing), "\n";
221
222 produces output
223
224 {"Yes":1,"No":0}
225 {"Yes":true,"No":false}
226
227 (This example is included as examples/boolean.pl
228 <https://fastapi.metacpan.org/source/BKB/JSON-
229 Create-0.35/examples/boolean.pl> in the distribution.)
230
231 If you prefer to take over all object handling yourself, there is also
232 "obj_handler", which overrides what is set with "bool".
233
234 Interoperability
235
236 The boolean values of the following Perl modules can interoperate with
237 JSON::Create.
238
239 boolean
240 $jc->bool ('boolean');
241
242 JSON::Tiny
243 $jc->bool ('JSON::Tiny::_Bool');
244
245 Round trip compatibility is also confirmed for JSON::Tiny version
246 0.54.
247
248 JSON::PP
249 $jc->bool ('JSON::PP::Boolean');
250
251 Round trip compatibility is also confirmed for JSON::PP version
252 2.27300.
253
254 Types::Serialiser
255 $jc->bool ('JSON::PP::Boolean');
256
257 Please note the above is not a typo, JSON::PP::Boolean is the
258 correct object type for Types::Serialiser. To confirm this, try
259
260 print ref $Types::Serialiser::false;
261
262 Mojo::JSON
263 $jc->bool ('JSON::PP::Boolean', 'Mojo::JSON::_Bool');
264
265 Round trip compatibility is also confirmed for Mojo::JSON version
266 8.65.
267
268 The current version of Mojo::JSON (Mojolicious version 8.65) uses
269 "JSON::PP::Boolean" for true and false values. Older versions used
270 their own type, "Mojo::JSON::_Bool".
271
272 JSON::Create's compatibility tests for Mojo::JSON compatibility are
273 available only in the git repository as xt/mojo-json.t, rather than
274 in the CPAN release, because different versions of Mojolicious
275 differ a lot in not only function names but also variable names, as
276 seen above.
277
278 You can handle multiple modules with the same object:
279
280 $jc->bool (qw/boolean JSON::Tiny::_Bool JSON::PP::Boolean/);
281
282 The compatibility of the above modules can be confirmed by running the
283 test script t/bool.t in the distribution. However, JSON::Create does
284 not install these modules, so unless you have installed them yourself,
285 the tests will just be skipped.
286
287 More modules will be added to this list as time permits.
288
289 cmp
290 Set a user-defined routine to be used with the "sort" option.
291
292 Sorting the keys of objects in a user-defined order will reduce the
293 performance of the module. The built-in variables $a and $b are not
294 available to your sort routine, so you need to get the arguments
295 yourself.
296
297 Sorting object elements case-independently
298
299 use utf8;
300 use FindBin '$Bin';
301 use JSON::Create;
302 my $jc = JSON::Create->new (sort => 1, indent => 1);
303 $jc->cmp (\&uccmp);
304 my %emojis = (
305 lifeforms => {
306 Kingkong => 'π¦',
307 goat => 'π',
308 elephant => 'π',
309 Grape => 'π',
310 Watermelon => 'π',
311 melon => 'π',
312 # What if life exists based on another element? π
313 siliconbased => 'β',
314 },
315 );
316 print $jc->run (\%emojis);
317
318 sub uccmp
319 {
320 my ($a, $b) = @_;
321 return uc ($a) cmp uc ($b);
322 }
323
324 produces output
325
326 {
327 "lifeforms":{
328 "elephant":"π",
329 "goat":"π",
330 "Grape":"π",
331 "Kingkong":"π¦",
332 "melon":"π",
333 "siliconbased":"β",
334 "Watermelon":"π"
335 }
336 }
337
338 (This example is included as examples/cmp.pl
339 <https://fastapi.metacpan.org/source/BKB/JSON-
340 Create-0.35/examples/cmp.pl> in the distribution.)
341
342 This method was added in version 0.29 of the module.
343
344 downgrade_utf8
345 $jc->downgrade_utf8 (1);
346
347 If this is set to a true value, the return value of "create_json" or
348 "create" is never upgraded to character strings, or "utf8". This
349 overrides the default behaviour, which is to upgrade the output to
350 "utf8" if any part of the input is "utf8", or if the user has requested
351 replacement with "replace_bad_utf8" and there are bad characters in the
352 user's input. See "UNICODE HANDLING" for details. All output of
353 JSON::Create is valid UTF-8, regardless of what this flag is set to.
354 See "Output is valid UTF-8".
355
356 This method was added in version 0.18 of the module.
357
358 escape_slash
359 $jc->escape_slash (1);
360
361 Call this with a true value to make the slash (known as the "solidus"
362 in the JSON specification) be escaped with a backslash, so "/" gets
363 turned into "\/". Call this with any false value to make the slash not
364 be escaped (the default behaviour).
365
366 Escaping slashes
367
368 use JSON::Create;
369 my $jc = JSON::Create->new ();
370 my $in = {'/dog/' => '/run/'};
371 print $jc->run ($in), "\n";
372 $jc->escape_slash (1);
373 print $jc->run ($in), "\n";
374 $jc->escape_slash (0);
375 print $jc->run ($in), "\n";
376
377 produces output
378
379 {"/dog/":"/run/"}
380 {"\/dog\/":"\/run\/"}
381 {"/dog/":"/run/"}
382
383 (This example is included as examples/escape-slash.pl
384 <https://fastapi.metacpan.org/source/BKB/JSON-
385 Create-0.35/examples/escape-slash.pl> in the distribution.)
386
387 See also "Other escapes".
388
389 This method was added in version 0.07 of the module.
390
391 indent
392 $jc->indent (1);
393
394 Add whitespace indentation to the output. The formula applied is to add
395 a newline plus indentation after each opening bracket, add the same
396 after each comma, and add the same before each closing bracket. Tabs
397 are used for all indentation. The number of tabs is decided by the
398 number of brackets open.
399
400 Example of indentation
401
402 use JSON::Create;
403 my %thing = ("it's your thing" => [qw! do what you !, {wanna => 'do'}],
404 "I can't tell you" => [{who => 2}, qw! sock it!, 2]);
405 my $jc = JSON::Create->new ();
406 $jc->indent (1);
407 print $jc->run (\%thing);
408
409 produces output
410
411 {
412 "it's your thing":[
413 "do",
414 "what",
415 "you",
416 {
417 "wanna":"do"
418 }
419 ],
420 "I can't tell you":[
421 {
422 "who":2
423 },
424 "sock",
425 "it",
426 2
427 ]
428 }
429
430 (This example is included as examples/indent.pl
431 <https://fastapi.metacpan.org/source/BKB/JSON-
432 Create-0.35/examples/indent.pl> in the distribution.)
433
434 Reformatting the indentation
435
436 Users who prefer a different style of indentation should easily be able
437 to modify this output to their needs using simple substitutions, for
438 example "s/^(\t+)/ " " x length ($1) /gesm;" will convert from tabs to
439 two space indentation.
440
441 use JSON::Create;
442 my %thing = ("it's your thing" => [qw! do what you !, {wanna => 'do'}],
443 "I can't tell you" => [{who => 2}, qw! sock it!, 2]);
444 my $jc = JSON::Create->new ();
445 $jc->indent (1);
446 my $out = $jc->run (\%thing);
447 $out =~ s/^(\t+)/ " " x length ($1) /gesm;
448 print $out;
449
450 produces output
451
452 {
453 "I can't tell you":[
454 {
455 "who":2
456 },
457 "sock",
458 "it",
459 2
460 ],
461 "it's your thing":[
462 "do",
463 "what",
464 "you",
465 {
466 "wanna":"do"
467 }
468 ]
469 }
470
471 (This example is included as examples/indent-format.pl
472 <https://fastapi.metacpan.org/source/BKB/JSON-
473 Create-0.35/examples/indent-format.pl> in the distribution.)
474
475 This method was added in version 0.27 of the module.
476
477 no_javascript_safe
478 $jc->no_javascript_safe (1);
479
480 If called with a true value, this switches off JavaScript protection in
481 the output JSON. If called with a false value, the JavaScript
482 protection is switched on again.
483
484 Switching JavaScript-safety on and off
485
486 use JSON::Create;
487 my $in = ["\x{2028}"];
488 my $jc = JSON::Create->new ();
489 print $jc->run ($in), "\n";
490 $jc->no_javascript_safe (1);
491 print $jc->run ($in), "\n";
492
493 produces output
494
495 ["\u2028"]
496 ["β¨"]
497
498 (This example is included as examples/js-safe.pl
499 <https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/js-
500 safe.pl> in the distribution.)
501
502 See also "U+2028 and U+2029 (JavaScript clashes)".
503
504 non_finite_handler
505 $jc->non_finite_handler (\& handler);
506
507 This overrides the default behaviour for handling non-finite floating
508 point numbers, in other words NaN (not a number) and negative or
509 positive infinity, with a user-defined routine. The default behaviour
510 of this module is described at "Floating point numbers".
511
512 The routine "handler" is supplied with the non-finite number as its
513 sole argument, and returns one argument, the output JSON.
514
515 Using null for infinity and NaN
516
517 To always use "null" in place of the default, supply a function like
518 the following:
519
520 use JSON::Create;
521 my $bread = { 'curry' => -sin(9**9**9) };
522 my $jcnfh = JSON::Create->new ();
523 print $jcnfh->run ($bread), "\n";
524 $jcnfh->non_finite_handler(sub { return 'null'; });
525 print $jcnfh->run ($bread), "\n";
526
527 produces output
528
529 {"curry":"nan"}
530 {"curry":null}
531
532 (This example is included as examples/non-finite-handler.pl
533 <https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/non-
534 finite-handler.pl> in the distribution.)
535
536 β’ Calling convention
537
538 The non_finite_handler routine is passed a single argument and is
539 expected to return a single argument, the JSON to output. It is
540 called in scalar context. In other words, the call looks like the
541 following:
542
543 $json = &{$jc->{non_finite_handler}} ($item);
544
545 To pass or return multiple values via the "non_finite_handler"
546 callback, use a closure. See the discussion at "obj" for an
547 example.
548
549 β’ Returning undef halts processing
550
551 If your handler returns the undefined value, "create" prints a
552 warning "Undefined value from user routine", halts further
553 processing of the input, and returns the undefined value.
554
555 β’ Delete the handler with any false value
556
557 To remove the handler, simply call the function without an
558 argument,
559
560 $jc->non_finite_handler ();
561
562 or with a false argument:
563
564 $jc->non_finite_handler (0);
565
566 The behaviour then reverts to the default.
567
568 β’ Checking the output JSON
569
570 The JSON output by your handler may be checked for validity by
571 switching on validation using "validate". If you do not use this,
572 and your return value happens to contain invalid UTF-8, you may see
573 the error "Invalid UTF-8 from user routine". Please see "UTF-8
574 validation of user-supplied JSON" for more about this error.
575
576 β’ Exception handling
577
578 Exceptions ("die") thrown within "non_finite_handler" callbacks are
579 not caught by "create" but passed through to the parent. Please see
580 the discussion at "obj" for an example.
581
582 This method was added in version 0.17 of the module.
583
584 obj
585 $jc->obj ('Zilog::Z80' => sub { my ($obj) = @_; print "\"Z80\""; });
586
587 Register JSON generators for Perl objects. When JSON::Create finds an
588 object with a registered type, it will call the method you have
589 supplied.
590
591 The argument to "obj" is a hash. The keys are object names, and the
592 corresponding values are code references to the JSON serializer for
593 that object:
594
595 $jc->obj (
596 'My::Object' => \& object_to_json,
597 );
598
599 The output is passed through to the output string unaltered. To have
600 your JSON output checked for validity, use the "validate" option.
601
602 The function is called with the object reference as its only argument,
603 as if called like this:
604
605 my $user_json = $my_object->object_to_json ();
606
607 The return value of the function, "object_to_json" in the above
608 example, must be a single value, a string containing the object's JSON
609 encoding.
610
611 use JSON::Create;
612 my $jc = JSON::Create->new ();
613 package Zilog::Z80;
614 sub new { return bless { memory => '64 kbytes' }; }
615 sub to_json {
616 my ($self) = @_;
617 return '"I can address as many as '.$self->{memory}.' of memory"';
618 }
619 1;
620 package main;
621 my $zilog = Zilog::Z80->new ();
622 my %stuff = (zilog => $zilog);
623 print $jc->run (\%stuff), "\n";
624 # Set up our object's method for printing JSON.
625 $jc->obj (
626 'Zilog::Z80' => \& Zilog::Z80::to_json,
627 );
628 print $jc->run (\%stuff), "\n";
629
630 produces output
631
632 {"zilog":{"memory":"64 kbytes"}}
633 {"zilog":"I can address as many as 64 kbytes of memory"}
634
635 (This example is included as examples/zilog.pl
636 <https://fastapi.metacpan.org/source/BKB/JSON-
637 Create-0.35/examples/zilog.pl> in the distribution.)
638
639 The function is called "in scalar context", so
640
641 use JSON::Create;
642 my $jc = JSON::Create->new ();
643 $jc->validate (1);
644 $jc->type_handler (sub {
645 return ('"a"', '"b"', '"c"');
646 });
647 print $jc->run ({ x => *STDOUT });
648
649 produces output
650
651 {"x":"c"}
652
653 (This example is included as examples/too-many-values.pl
654 <https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/too-
655 many-values.pl> in the distribution.)
656
657 If you need to pass or return more than a single argument, use a
658 closure:
659
660 use JSON::Create;
661 package My::Cool::Object;
662 sub new { return bless {}; }
663 sub serialize { return ('true', 'false'); };
664 1;
665 package main;
666 my $object = My::Cool::Object->new ();
667 my $jc = JSON::Create->new ();
668 my ($arg1, $arg2);
669 $jc->obj (
670 'My::Cool::Object' => sub {
671 my ($obj) = @_;
672 my ($value1, $value2) = My::Cool::Object::serialize ($obj, $arg1, $arg2);
673 return $value2;
674 },
675 );
676 print $jc->run ({cool => $object});
677
678 produces output
679
680 {"cool":false}
681
682 (This example is included as examples/closure.pl
683 <https://fastapi.metacpan.org/source/BKB/JSON-
684 Create-0.35/examples/closure.pl> in the distribution.)
685
686 Throwing an exception in your callback
687
688 Exceptions (fatal errors) are not caught by JSON::Create, so if you
689 want to halt the execution of JSON::Create, you can throw an exception
690 within your callback.
691
692 use JSON::Create;
693 package Funky::Monkey::Baby; sub new {return bless {};} 1;
694 package main;
695 my $jc = JSON::Create->new ();
696 $jc->obj (
697 'Funky::Monkey::Baby' => sub {
698 die "There is no such thing as a funky monkey baby";
699 },
700 );
701 eval {
702 $jc->run ({fmb => Funky::Monkey::Baby->new ()});
703 };
704 if ($@) {
705 print "$@\n";
706 }
707
708 produces output
709
710 There is no such thing as a funky monkey baby at /usr/home/ben/projects/json-create/examples/exception.pl line 10.
711
712 (This example is included as examples/exception.pl
713 <https://fastapi.metacpan.org/source/BKB/JSON-
714 Create-0.35/examples/exception.pl> in the distribution.)
715
716 If you prefer to take over all object handling yourself, there is also
717 "obj_handler".
718
719 If your handler returns the undefined value, "create" prints a warning
720 "Undefined value from user routine", halts further processing of the
721 input, and returns the undefined value.
722
723 obj_handler
724 $jc->obj_handler (\& my_obj_handler);
725
726 Supply an object handler. If you supply this, all objects will be
727 handled by your handler. For example, you can replace all objects with
728 'null' or die if an object is found.
729
730 β’ Calling convention
731
732 The obj_handler routine is passed a single argument and is expected
733 to return a single argument, the JSON to output. It is called in
734 scalar context. In other words, the call looks like the following:
735
736 $json = &{$jc->{obj_handler}} ($item);
737
738 To pass or return multiple values via the "obj_handler" callback,
739 use a closure. See the discussion at "obj" for an example.
740
741 β’ Returning undef halts processing
742
743 If your handler returns the undefined value, "create" prints a
744 warning "Undefined value from user routine", halts further
745 processing of the input, and returns the undefined value.
746
747 β’ Delete the handler with any false value
748
749 To remove the handler, simply call the function without an
750 argument,
751
752 $jc->obj_handler ();
753
754 or with a false argument:
755
756 $jc->obj_handler (0);
757
758 The behaviour then reverts to the default.
759
760 β’ Checking the output JSON
761
762 The JSON output by your handler may be checked for validity by
763 switching on validation using "validate". If you do not use this,
764 and your return value happens to contain invalid UTF-8, you may see
765 the error "Invalid UTF-8 from user routine". Please see "UTF-8
766 validation of user-supplied JSON" for more about this error.
767
768 β’ Exception handling
769
770 Exceptions ("die") thrown within "obj_handler" callbacks are not
771 caught by "create" but passed through to the parent. Please see the
772 discussion at "obj" for an example.
773
774 Turning various types of object into JSON
775
776 Here is an example of handling various types of object with a user-
777 supplied handler:
778
779 use utf8;
780 use FindBin '$Bin';
781 use JSON::Create;
782 package Monkey::Shines;
783 sub new { return bless {}; }
784 1;
785 package Monkey::Shines::Bool;
786 sub true { my $monkey = 1; return bless \$monkey; }
787 sub false { my $monkey = 0; return bless \$monkey; }
788 1;
789 package main;
790 my $monkeys = {
791 CuriousGeorge => Monkey::Shines->new (),
792 KingKong => Monkey::Shines::Bool->true (),
793 FunkyKong => Monkey::Shines::Bool->false (),
794 PeterTork => "Monkees",
795 };
796 my $obj_handler = sub {
797 my ($obj) = @_;
798 if (ref ($obj) =~ /bool/i) {
799 return $$obj ? 'true' : 'false';
800 }
801 else {
802 return 'null';
803 }
804 };
805 my $jc = JSON::Create->new (indent => 1, sort => 1);
806 print $jc->run ($monkeys), "\n";
807 $jc->obj_handler ($obj_handler);
808 print $jc->run ($monkeys), "\n";
809 $jc->obj_handler ();
810 print $jc->run ($monkeys), "\n";
811
812 produces output
813
814 {
815 "CuriousGeorge":{},
816 "FunkyKong":0,
817 "KingKong":1,
818 "PeterTork":"Monkees"
819 }
820
821 {
822 "CuriousGeorge":null,
823 "FunkyKong":false,
824 "KingKong":true,
825 "PeterTork":"Monkees"
826 }
827
828 {
829 "CuriousGeorge":{},
830 "FunkyKong":0,
831 "KingKong":1,
832 "PeterTork":"Monkees"
833 }
834
835 (This example is included as examples/obj-handler.pl
836 <https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/obj-
837 handler.pl> in the distribution.)
838
839 Turning everything into JSON
840
841 Here is an example of a "try harder" routine which does something like
842 the JSON module does, by looking for methods on all objects:
843
844 use utf8;
845 use FindBin '$Bin';
846 use JSON::Create 'create_json';
847 use Mojo::URL;
848 use Path::Tiny;
849
850 sub try_harder
851 {
852 my ($obj) = @_;
853 my $type = ref $obj;
854 if ($obj->can ('TO_JSON')) {
855 print "Jsonifying $type with 'TO_JSON'.\n";
856 return create_json ($obj->TO_JSON ());
857 }
858 elsif ($obj->can ('to_string')) {
859 print "Stringifying $type with 'to_string'.\n";
860 # The call to "create_json" makes sure that the string is
861 # valid as a JSON string.
862 return create_json ($obj->to_string ());
863 }
864 else {
865 return create_json ($obj);
866 }
867 }
868
869 my $jc = JSON::Create->new (indent => 1, sort => 1, validate => 1);
870 $jc->obj_handler (\& try_harder);
871 print $jc->run ({
872 url => Mojo::URL->new('http://sri:foo@example.com:3000/foo?foo=bar#23'),
873 path => path ('/home/ben/software/install/bin/perl'),
874 }), "\n";
875
876 produces output
877
878 Jsonifying Path::Tiny with 'TO_JSON'.
879 Stringifying Mojo::URL with 'to_string'.
880 {
881 "path":"/home/ben/software/install/bin/perl",
882 "url":"http://example.com:3000/foo?foo=bar#23"
883 }
884
885 (This example is included as examples/try-harder.pl
886 <https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/try-
887 harder.pl> in the distribution.)
888
889 This "obj_handler" overrides whatever you have set with "bool" or
890 "obj". Currently, it does not print a warning about this. See "BUGS".
891 The routine you use to handle objects may be the same as the routine
892 you use to handle types. See "type_handler". For more details about the
893 callbacks, see "obj".
894
895 This method was added in version 0.13 of the module.
896
897 replace_bad_utf8
898 $jc->replace_bad_utf8 (1);
899
900 Replace invalid UTF-8 in the inputs with the Unicode replacement
901 character U+FFFD, rather than produce the warning or error "Invalid
902 UTF-8".
903
904 If "replace_bad_utf8" is used on input containing only strings not
905 marked as character strings, and bad UTF-8 is found, JSON::Create marks
906 the output as a character string. Otherwise the replacement character
907 itself is just a series of broken bytes. This behaviour can be altered
908 with the method "downgrade_utf8".
909
910 This method was added in version 0.12 of the module.
911
912 set_fformat
913 $jc->set_fformat ('%e');
914
915 This sets the printf-style format string used to print floating point
916 numbers. This is validated and a warning printed if the format cannot
917 be used. The format is also restricted to a maximum length to prevent
918 buffer overflows within the module.
919
920 Setting the format of floating point numbers
921
922 use JSON::Create;
923 my $jc = JSON::Create->new ();
924 my @array = (1000000000.0,3.141592653589793238462643383279502884197169399375105820974944592307816406,0.000000001);
925 print $jc->run (\@array), "\n";
926 $jc->set_fformat ('%.3f');
927 print $jc->run (\@array), "\n";
928 $jc->set_fformat ('%E');
929 print $jc->run (\@array), "\n";
930 $jc->set_fformat ();
931 print $jc->run (\@array), "\n";
932
933 produces output
934
935 [1e+09,3.14159,1e-09]
936 [1000000000.000,3.142,0.000]
937 [1.000000E+09,3.141593E+00,1.000000E-09]
938 [1e+09,3.14159,1e-09]
939
940 (This example is included as examples/set-fformat.pl
941 <https://fastapi.metacpan.org/source/BKB/JSON-Create-0.35/examples/set-
942 fformat.pl> in the distribution.)
943
944 This method was added in version 0.07 of the module.
945
946 sort
947 $jc->sort (1);
948
949 Sort hash keys. The default is to use Perl's string sorting. Use "cmp"
950 to supply your own sorting routine. This does not affect the order of
951 array elements, only hash keys.
952
953 JSON with indentation and sorted keys
954
955 use utf8;
956 use JSON::Create;
957
958 my %emojis = (
959 animals => {
960 kingkong => 'π¦',
961 goat => 'π',
962 elephant => 'π',
963 },
964 fruit => {
965 grape => 'π',
966 watermelon => 'π',
967 melon => 'π',
968 },
969 baka => { # Japanese words
970 'γ°' => 'γ',
971 'γ' => 'γ»',
972 'γΎ' => 'γ¬γ',
973 },
974 );
975 my $jc = JSON::Create->new ();
976
977 my @moons = qw!π π π π π π π π!;
978 my $i = 0;
979 for (@moons) {
980 $emojis{moons}{$_} = $i;
981 $i++;
982 }
983
984 $jc->sort (1);
985 $jc->indent (1);
986 print $jc->run (\%emojis);
987
988 produces output
989
990 {
991 "animals":{
992 "elephant":"π",
993 "goat":"π",
994 "kingkong":"π¦"
995 },
996 "baka":{
997 "γ":"γ»",
998 "γ°":"γ",
999 "γΎ":"γ¬γ"
1000 },
1001 "fruit":{
1002 "grape":"π",
1003 "melon":"π",
1004 "watermelon":"π"
1005 },
1006 "moons":{
1007 "π":0,
1008 "π":1,
1009 "π":2,
1010 "π":3,
1011 "π":4,
1012 "π":5,
1013 "π":6,
1014 "π":7
1015 }
1016 }
1017
1018 (This example is included as examples/sort.pl
1019 <https://fastapi.metacpan.org/source/BKB/JSON-
1020 Create-0.35/examples/sort.pl> in the distribution.)
1021
1022 This method was added in version 0.29 of the module.
1023
1024 type_handler
1025 $jc->type_handler (sub {return 'null'});
1026
1027 By default, when JSON::Create encounters a variable of a type which it
1028 doesn't know what to do with, such as a glob or code reference, it
1029 prints a warning and returns an undefined value. See "Code, regexes,
1030 and other references". The method "type_handler" sets up a callback
1031 which is called when a variable of an unhandled type is found in the
1032 input. For example, to put the JSON literal "null" in the output when a
1033 reference to a variable of an unhandled type is encountered, rather
1034 than print an error, the above example will do it.
1035
1036 β’ Calling convention
1037
1038 The type_handler routine is passed a single argument and is
1039 expected to return a single argument, the JSON to output. It is
1040 called in scalar context. In other words, the call looks like the
1041 following:
1042
1043 $json = &{$jc->{type_handler}} ($item);
1044
1045 To pass or return multiple values via the "type_handler" callback,
1046 use a closure. See the discussion at "obj" for an example.
1047
1048 β’ Returning undef halts processing
1049
1050 If your handler returns the undefined value, "create" prints a
1051 warning "Undefined value from user routine", halts further
1052 processing of the input, and returns the undefined value.
1053
1054 β’ Delete the handler with any false value
1055
1056 To remove the handler, simply call the function without an
1057 argument,
1058
1059 $jc->type_handler ();
1060
1061 or with a false argument:
1062
1063 $jc->type_handler (0);
1064
1065 The behaviour then reverts to the default.
1066
1067 β’ Checking the output JSON
1068
1069 The JSON output by your handler may be checked for validity by
1070 switching on validation using "validate". If you do not use this,
1071 and your return value happens to contain invalid UTF-8, you may see
1072 the error "Invalid UTF-8 from user routine". Please see "UTF-8
1073 validation of user-supplied JSON" for more about this error.
1074
1075 β’ Exception handling
1076
1077 Exceptions ("die") thrown within "type_handler" callbacks are not
1078 caught by "create" but passed through to the parent. Please see the
1079 discussion at "obj" for an example.
1080
1081 Ways to handle types
1082
1083 The following example shows a few possibilities for handling types:
1084
1085 use utf8;
1086 use FindBin '$Bin';
1087 use JSON::Create 'create_json';
1088 my %crazyhash = (
1089 'code' => sub { return "κ°λ¨μ€νμΌ"; },
1090 'regex' => qr/.*/,
1091 'glob' => *STDOUT,
1092 );
1093 # Let's validate the output of the subroutine below.
1094 my $jc = JSON::Create->new (validate => 1, indent => 1, sort => 1);
1095 # Try this one weird old trick to convert your Perl type.
1096 $jc->type_handler (
1097 sub {
1098 my ($thing) = @_;
1099 my $value;
1100 my $type = ref ($thing);
1101 if ($type eq 'CODE') {
1102 $value = &$thing;
1103 }
1104 else {
1105 $value = "$thing";
1106 }
1107 return create_json ({ type => $type, value => $value, },
1108 indent => 1, sort => 1);
1109 }
1110 );
1111 print $jc->run (\%crazyhash), "\n";
1112
1113 produces output
1114
1115 {
1116 "code":{
1117 "type":"CODE",
1118 "value":"κ°λ¨μ€νμΌ"
1119 },
1120 "glob":{
1121 "type":"GLOB",
1122 "value":"GLOB(0x209a82a0)"
1123 },
1124 "regex":{
1125 "type":"Regexp",
1126 "value":"(?^:.*)"
1127 }
1128 }
1129
1130 (This example is included as examples/type-handler.pl
1131 <https://fastapi.metacpan.org/source/BKB/JSON-
1132 Create-0.35/examples/type-handler.pl> in the distribution.)
1133
1134 If the "strict" option is chosen, this method is also passed scalar
1135 references.
1136
1137 use JSON::Create;
1138 my $jc = JSON::Create->new ();
1139 $jc->strict (1);
1140 print "Before: ", $jc->run (\1), "\n";
1141 $jc->type_handler (sub {
1142 my ($thing) = @_;
1143 if (ref $thing eq 'SCALAR') {
1144 return $$thing;
1145 }
1146 });
1147 print "After: ", $jc->run (\1), "\n";
1148
1149 produces output
1150
1151 Input's type cannot be serialized to JSON at /usr/home/ben/projects/json-create/examples/type-handler-scalar.pl line 7.
1152 Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/type-handler-scalar.pl line 7.
1153 Before:
1154 After: 1
1155
1156 (This example is included as examples/type-handler-scalar.pl
1157 <https://fastapi.metacpan.org/source/BKB/JSON-
1158 Create-0.35/examples/type-handler-scalar.pl> in the distribution.)
1159
1160 This method was added in version 0.10 of the module.
1161
1162 unicode_escape_all
1163 $jc->unicode_escape_all (1);
1164
1165 Call this with a true value to make all Unicode characters be escaped
1166 into the "\u3000" format. A false value switches that off again.
1167
1168 Escape all Unicode
1169
1170 use JSON::Create;
1171 use utf8;
1172 my $jc = JSON::Create->new ();
1173 my $in = 'θ΅€γΓΆοΌ‘βΟͺ';
1174 print $jc->run ($in), "\n";
1175 $jc->unicode_escape_all (1);
1176 print $jc->run ($in), "\n";
1177 $jc->unicode_upper (1);
1178 print $jc->run ($in), "\n";
1179 $jc->unicode_escape_all (0);
1180 print $jc->run ($in), "\n";
1181
1182 produces output
1183
1184 "θ΅€γΓΆοΌ‘βΟͺ"
1185 "\u8d64\u30d6\u00f6\uff21\u2182\u03ea"
1186 "\u8D64\u30D6\u00F6\uFF21\u2182\u03EA"
1187 "θ΅€γΓΆοΌ‘βΟͺ"
1188
1189 (This example is included as examples/escape-all.pl
1190 <https://fastapi.metacpan.org/source/BKB/JSON-
1191 Create-0.35/examples/escape-all.pl> in the distribution.)
1192
1193 Output is always UTF-8
1194
1195 Note that JSON::Create contains its own UTF-8 validation, and this
1196 escaping is applied regardless of whether Perl marks the bytes as
1197 "utf8" or not:
1198
1199 use JSON::Create;
1200 no utf8;
1201 my $jc = JSON::Create->new ();
1202 my $in = 'θ΅€γΓΆοΌ‘βΟͺ';
1203 print $jc->run ($in), "\n";
1204 $jc->unicode_escape_all (1);
1205 print $jc->run ($in), "\n";
1206 $jc->unicode_upper (1);
1207 print $jc->run ($in), "\n";
1208 $jc->unicode_escape_all (0);
1209 print $jc->run ($in), "\n";
1210
1211 produces output
1212
1213 "θ΅€γΓΆοΌ‘βΟͺ"
1214 "\u8d64\u30d6\u00f6\uff21\u2182\u03ea"
1215 "\u8D64\u30D6\u00F6\uFF21\u2182\u03EA"
1216 "θ΅€γΓΆοΌ‘βΟͺ"
1217
1218 (This example is included as examples/escape-all-no-utf8.pl
1219 <https://fastapi.metacpan.org/source/BKB/JSON-
1220 Create-0.35/examples/escape-all-no-utf8.pl> in the distribution.)
1221
1222 See also "Input strings must be UTF-8".
1223
1224 unicode_upper
1225 $jc->unicode_upper (1);
1226
1227 Call this with a true value to make Unicode escapes use upper case
1228 letters in the hexadecimal. See the example under "unicode_escape_all".
1229
1230 validate
1231 $jc->validate (1);
1232
1233 If this is called with a true value, JSON::Create validates the user-
1234 generated JSON given by the callbacks registered with "obj",
1235 "type_handler", "obj_handler" and "non_finite_handler". The validation
1236 is done via the routine "assert_valid_json" of JSON::Parse, so that
1237 module must be installed, otherwise the call to "validate" will fail.
1238 This also validates that the return value contains only valid UTF-8.
1239
1240 If JSON::Parse is installed, and the JSON fails to validate, a warning
1241 will be produced containing the invalid JSON string and the error
1242 produced by "assert_valid_json", and the return value will be
1243 undefined.
1244
1245 This method was added in version 0.07 of the module.
1246
1248 This section details what conversions are applied to the various inputs
1249 to produce outputs.
1250
1251 Hashes
1252 JSON::Create turns associative arrays into JSON objects. The keys are
1253 written into JSON as strings, with control characters escaped. The
1254 order of the keys is as they are supplied by Perl.
1255
1256 use JSON::Create 'create_json';
1257 my %example = (
1258 x => 1,
1259 y => 2,
1260 z => 3,
1261 );
1262 print create_json (\%example);
1263
1264 produces output
1265
1266 {"y":2,"x":1,"z":3}
1267
1268 (This example is included as examples/hash.pl
1269 <https://fastapi.metacpan.org/source/BKB/JSON-
1270 Create-0.35/examples/hash.pl> in the distribution.)
1271
1272 Nested hashes are recursively followed:
1273
1274 use JSON::Create 'create_json';
1275 my %example = (
1276 x => {
1277 y => 2,
1278 z => 3,
1279 },
1280 a => {
1281 b => 4,
1282 c => 5,
1283 },
1284 );
1285 print create_json (\%example);
1286
1287 produces output
1288
1289 {"x":{"z":3,"y":2},"a":{"b":4,"c":5}}
1290
1291 (This example is included as examples/nested-hash.pl
1292 <https://fastapi.metacpan.org/source/BKB/JSON-
1293 Create-0.35/examples/nested-hash.pl> in the distribution.)
1294
1295 Arrays
1296 Arrays are converted to JSON arrays. The order of elements of the array
1297 is left unchanged.
1298
1299 use JSON::Create 'create_json';
1300 my @array = (1, 2, 2.5, qw/mocha dusty milky/, qw/Tico Rocky Pinky/);
1301 print create_json (\@array);
1302
1303 produces output
1304
1305 [1,2,2.5,"mocha","dusty","milky","Tico","Rocky","Pinky"]
1306
1307 (This example is included as examples/array.pl
1308 <https://fastapi.metacpan.org/source/BKB/JSON-
1309 Create-0.35/examples/array.pl> in the distribution.)
1310
1311 Nested arrays are recursively followed:
1312
1313 use JSON::Create 'create_json';
1314 my @array = ([1, 2, 2.5], [qw/mocha dusty milky/], [qw/Tico Rocky Pinky/]);
1315 print create_json (\@array);
1316
1317 produces output
1318
1319 [[1,2,2.5],["mocha","dusty","milky"],["Tico","Rocky","Pinky"]]
1320
1321 (This example is included as examples/nested-array.pl
1322 <https://fastapi.metacpan.org/source/BKB/JSON-
1323 Create-0.35/examples/nested-array.pl> in the distribution.)
1324
1325 Nested hashes and arrays are converted similarly:
1326
1327 use JSON::Create 'create_json';
1328 my $nested = {
1329 numbers => [1, 2, 2.5, 99.99],
1330 cats => [qw/mocha dusty milky/],
1331 dogs => [qw/Tico Rocky Pinky/],
1332 fruit => {
1333 thai => 'pineapple',
1334 japan => 'persimmon',
1335 australia => 'orange',
1336 },
1337 };
1338 print create_json ($nested, sort => 1, indent => 1);
1339
1340 produces output
1341
1342 {
1343 "cats":[
1344 "mocha",
1345 "dusty",
1346 "milky"
1347 ],
1348 "dogs":[
1349 "Tico",
1350 "Rocky",
1351 "Pinky"
1352 ],
1353 "fruit":{
1354 "australia":"orange",
1355 "japan":"persimmon",
1356 "thai":"pineapple"
1357 },
1358 "numbers":[
1359 1,
1360 2,
1361 2.5,
1362 99.99
1363 ]
1364 }
1365
1366 (This example is included as examples/nested.pl
1367 <https://fastapi.metacpan.org/source/BKB/JSON-
1368 Create-0.35/examples/nested.pl> in the distribution.)
1369
1370 Scalars
1371 Non-reference Perl scalars are converted to JSON strings or numbers,
1372 depending on what Perl thinks they contain.
1373
1374 Strings
1375
1376 As far as possible, strings are written as they are to the JSON.
1377
1378 JSON is Unicode, so all output is checked for Unicode validity.
1379 Further, this module insists on UTF-8. (See "Input strings must be
1380 UTF-8".) Invalid UTF-8 within input strings produces the error "Invalid
1381 UTF-8" and the undefined value is returned. This behaviour can be
1382 altered with the method "replace_bad_utf8". (For full details of the
1383 corner cases, see "UNICODE HANDLING".)
1384
1385 Some whitespace and control characters must be also escaped for the
1386 output to be valid JSON. (See "RFC 8259".)
1387
1388 In addition to this, "create_json_strict" or the "strict" option reject
1389 inputs containing non-ASCII bytes (bytes with values of from 128 to
1390 255) which are not marked as character strings.
1391
1392 Control characters and whitespace
1393
1394 To form valid JSON, bytes of value less than 0x20 in a Perl string must
1395 be converted into JSON escapes, either the whitespace escapes \b
1396 (backspace) \r, \t, \n, and \f, or the form \u0001 for other control
1397 characters. Further, the backslash must be written as "\\" and double
1398 quotes must be written as "\"".
1399
1400 This example demonstrates some of the necessary escaping:
1401
1402 use JSON::Create 'create_json';
1403 # An example string containing various things.
1404 my $weirdstring = {weird => "\t\r\n\x00 " . '"' . '\\' . '/' };
1405 print create_json ($weirdstring);
1406
1407 produces output
1408
1409 {"weird":"\t\r\n\u0000 \"\\/"}
1410
1411 (This example is included as examples/weirdstring.pl
1412 <https://fastapi.metacpan.org/source/BKB/JSON-
1413 Create-0.35/examples/weirdstring.pl> in the distribution.)
1414
1415 U+2028 and U+2029 (JavaScript clashes)
1416
1417 my $out = create_json (["\x{2028}"]);
1418 # $out = '["\u2028"]'
1419
1420 Although it is not required by the JSON standard, JSON::Create by
1421 default escapes Unicode code points U+2028 and U+2029 as "\u2028" and
1422 "\u2029" for JavaScript compatibility. This behaviour can be altered
1423 with the method "no_javascript_safe".
1424
1425 This escaping is necessary for JavaScript because of a clash between
1426 the JSON standard and the JavaScript (ECMAScript) standard. The
1427 characters U+2028 ("LINE SEPARATOR" in the Unicode standard) and U+2029
1428 ("PARAGRAPH SEPARATOR" in the Unicode standard) are valid within JSON,
1429 as defined by "RFC 8259", but invalid within JavaScript strings, as
1430 defined by the ECMA standard (See ECMA Standard ECMA-262, "ECMAScript
1431 Language Specification", 3rd Edition, section 7.3 "Line Terminators").
1432
1433 Other escapes
1434
1435 The forward slash, /, known as "solidus" in the JSON specification,
1436 does not have to be escaped, and JSON::Create's default is not to
1437 escape it. This behaviour can be altered with the method
1438 "escape_slash".
1439
1440 Other Unicode values are not escaped. This behaviour can be altered
1441 with the method "unicode_escape_all".
1442
1443 Integers
1444
1445 Integers are printed in the usual way. Perl may interpret an integer
1446 with a very large absolute value to be a floating point number, and
1447 this module will print it out as such. See also "Context-dependent
1448 variables" for the handling of variables with both string and integer
1449 values.
1450
1451 Floating point numbers
1452
1453 Finite floating point numbers are printed using printf formatting via
1454 "%g", like
1455
1456 printf ("%g", $number);
1457
1458 This behaviour can be altered with the method "set_fformat"
1459
1460 JSON does not allow NaN or infinity as bare values. From page 6 of "RFC
1461 8259":
1462
1463 Numeric values that cannot be represented in the grammar below
1464 (such as Infinity and NaN) are not permitted.
1465
1466 "create_json" converts NaN (not a number) values to "nan" (the letters
1467 "nan" surrounded by double quotes), and positive and negative infinity
1468 to "inf" and "-inf" respectively.
1469
1470 "create_json_strict" disallows non-finite numbers. If a non-finite
1471 number appears within its input, it prints a warning "Non-finite number
1472 in input" and returns the undefined value:
1473
1474 use JSON::Create 'create_json_strict';
1475 print create_json_strict (9**9**9);
1476
1477 produces output
1478
1479 Non-finite number in input at /usr/home/ben/projects/json-create/blib/lib/JSON/Create.pm line 200.
1480 Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/strict-non-finite.pl line 5.
1481
1482 (This example is included as examples/strict-non-finite.pl
1483 <https://fastapi.metacpan.org/source/BKB/JSON-
1484 Create-0.35/examples/strict-non-finite.pl> in the distribution.)
1485
1486 A JSON::Create object created with "new" converts in the same way as
1487 "create_json". This behaviour can be altered with the method
1488 "non_finite_handler". If "strict" is specified, non-finite numbers are
1489 passed to "non_finite_handler" if it is set, and if not, it prints a
1490 warning "Non-finite number in input" and returns the undefined value.
1491
1492 The undefined value
1493
1494 Undefined values in the input are mapped to the JSON literal "null".
1495
1496 use JSON::Create 'create_json';
1497 print create_json ({a => undef, b => [undef, undef]}), "\n";
1498
1499 produces output
1500
1501 {"a":null,"b":[null,null]}
1502
1503 (This example is included as examples/undef.pl
1504 <https://fastapi.metacpan.org/source/BKB/JSON-
1505 Create-0.35/examples/undef.pl> in the distribution.)
1506
1507 Booleans
1508
1509 Booleans ("true" and "false") from input via JSON::Parse version 0.37
1510 or later will be turned into the outputs "true" and "false":
1511
1512 use JSON::Parse '0.38', 'parse_json';
1513 use JSON::Create 'create_json';
1514 my $in = parse_json ('[true,false,"boo"]');
1515 print create_json ($in);
1516
1517 produces output
1518
1519 [true,false,"boo"]
1520
1521 (This example is included as examples/json-parse-bool.pl
1522 <https://fastapi.metacpan.org/source/BKB/JSON-
1523 Create-0.35/examples/json-parse-bool.pl> in the distribution.)
1524
1525 Other kinds of object can be converted to booleans using the method
1526 "bool" (see below).
1527
1528 Context-dependent variables
1529
1530 A context-dependent variable is a variable which may contain a string
1531 and a numerical value. Usually the string value is just a
1532 representation of the number, but it may not be. The behaviour in the
1533 case of a context-dependent variable is as follows.
1534
1535 If the variable contains a valid numerical value, the numerical value
1536 is used in the output JSON, rather than the string value. However, some
1537 modules, like "charinfo" in Unicode::UCD, return context-dependent hash
1538 values which have a non-number-like string under the key "script" with
1539 values such as "Latin" or "Common" but no valid numerical value,
1540 despite being marked as context-dependent variables. In such cases, the
1541 string value is used. (In terms of XS, if the scalar is marked as
1542 "SVt_PVIV" or "SVt_PVNV", the scalar is tested with "SvIOK" or "SvNOK"
1543 respectively, and if this is true the numerical value is used, if false
1544 the string value is used.)
1545
1546 Up to version 0.25, this module wrongly assumed that the string part of
1547 a context-dependent variable would always be a valid representation of
1548 a number, and the string was added to the output without quote marks.
1549 In version 0.26, checking was done to see if the string actually was a
1550 number. In version 0.27 this approach was abandoned and the numerical
1551 value was given precedence. In version 0.28 this was again altered for
1552 the sake of unusual cases like the "script" key returned by "charinfo"
1553 in Unicode::UCD, where the scalar is marked as having a numerical value
1554 but does not in fact contain a valid numerical value.
1555
1556 Other types
1557 JSON::Create is meant to provide serialization of data types. It does
1558 not provide built-in serialization of Perl objects and other non-data
1559 types, such as code references or regular expressions, beyond a few
1560 basic defaults. How to handle non-data types is left completely up to
1561 users. These basic defaults, and how to set up more extensive handling,
1562 are described in the following subsections.
1563
1564 Scalar references
1565
1566 "create_json" dereferences scalar references, then treats them as
1567 scalars in the way described in "Scalars".
1568
1569 "create_json_strict" rejects scalar references. Input containing a
1570 scalar reference causes a warning "Input's type cannot be serialized to
1571 JSON" and the undefined value to be returned.
1572
1573 A JSON::Create object created with "new" behaves as "create_json"
1574 unless the "strict" option is specified. If the strict option is
1575 specified, scalar references are passed through to "type_handler" if it
1576 is set, otherwise input containing a scalar reference causes a warning
1577 "Input's type cannot be serialized to JSON" and the undefined value to
1578 be returned.
1579
1580 Objects
1581
1582 "create_json" handles Perl objects as if non-object types. In other
1583 words, unless you specify object handling, it breaks encapsulation.
1584
1585 "create_json_strict" rejects input containing Perl objects. If the
1586 input contains an object (a blessed reference), a warning "Object
1587 cannot be serialized to JSON" is printed and the undefined value
1588 returned.
1589
1590 A JSON::Create object created with "new" can handle specified types of
1591 object with method "obj", or with a general object handler supplied via
1592 "obj_handler". By default it behaves like "create_json". If "strict" is
1593 chosen, it rejects input containing Perl objects unless the user sets a
1594 handler for them with "obj" or "obj_handler".
1595
1596 Code, regexes, and other references
1597
1598 A code or other reference (regexes, globs, etc.) in the input of
1599 "create_json" or "create_json_strict" prints a warning "Input's type
1600 cannot be serialized to JSON" and causes the entire return value to be
1601 the undefined value. This behaviour can be altered with the method
1602 "type_handler".
1603
1605 The module exports nothing except by request. Two functions,
1606 "create_json" and "create_json_strict", are exported on request. There
1607 is also an export tag "all" if you require both functions:
1608
1609 use JSON::Create ':all';
1610
1612 The module uses C internally, so you need a C compiler to install it.
1613 If the compiled library cannot be loaded, there is also a backup "pure
1614 Perl" module JSON::Create::PP in the distribution.
1615
1617 This section details JSON::Create's handling of Unicode within strings.
1618 This involves the distinction between two things with confusingly
1619 similar names, Perl character strings, "utf8", and the Unicode encoding
1620 "UTF-8".
1621
1622 UTF-8 only
1623 JSON::Create only consumes and produces the UTF-8 encoding of
1624 Unicode. If you need a different encoding, please use the Encode
1625 module to encode the output.
1626
1627 Input strings must be UTF-8
1628 All strings within the input must be UTF-8 encoded. This does not
1629 mean that the strings must be Perl character strings (Perl's
1630 "utf8"), it means that input strings must be valid UTF-8. Input
1631 strings can be either Perl character strings or bytes, but in
1632 either case the bytes of the string must be valid UTF-8.
1633
1634 To illustrate this, examine the following example:
1635
1636 use JSON::Create 'create_json';
1637 use utf8;
1638 $| = 1;
1639 print create_json ('θ΅€γΓΆοΌ‘βΟͺ'), "\n";
1640 no utf8;
1641 binmode STDOUT, ":raw";
1642 print create_json ('θ΅€γΓΆοΌ‘βΟͺ'), "\n";
1643 print create_json ("\x99\xff\x10"), "\n";
1644
1645 produces output
1646
1647 "θ΅€γΓΆοΌ‘βΟͺ"
1648 "θ΅€γΓΆοΌ‘βΟͺ"
1649 Invalid UTF-8 at /usr/home/ben/projects/json-create/blib/lib/JSON/Create.pm line 192.
1650 Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/valid-chars.pl line 12.
1651
1652 (This example is included as examples/valid-chars.pl
1653 <https://fastapi.metacpan.org/source/BKB/JSON-
1654 Create-0.35/examples/valid-chars.pl> in the distribution.)
1655
1656 The point here is that the UTF-8 validation is carried out
1657 regardless of whether Perl thinks that the input string is "utf8".
1658 The string in the third call to "create_json" is not marked as utf8
1659 by Perl but still fails as invalid UTF-8.
1660
1661 JSON::Create's insistence on UTF-8 within input strings is related
1662 to "Unicode upgrades are not done according to Perl conventions".
1663
1664 Output is valid UTF-8
1665 All of the output of either the function "create_json" or the
1666 method "create" is valid UTF-8. This does not mean that output
1667 strings are marked as Perl character strings ("utf8"), it means
1668 that the output has been validated as UTF-8.
1669
1670 There is one exception to this. In the case of user-generated JSON
1671 returned by "obj", "obj_handler", "type_handler" and
1672 "non_finite_handler", the parts of the output consisting of return
1673 values from user routines may be non-UTF-8-compliant if the user
1674 has not switched on validation with "validate", and there are no
1675 character strings ("utf8") anywhere in the input. However, if there
1676 are any Perl character strings ("utf8") anywhere in the input, and
1677 the user has not chosen "downgrade_utf8", JSON::Create validates
1678 the entire output as UTF-8, as described in "UTF-8 validation of
1679 user-supplied JSON".
1680
1681 Unicode upgrades are not done according to Perl conventions
1682 If a single string anywhere in the input is a Perl character
1683 string, in other words marked as "utf8", the entire output string
1684 is marked as a Perl character string, "utf8", without altering the
1685 non-"utf8" bytes. This is at odds with Perl conventions. Perl says
1686 that non-"utf8" strings actually consist of characters with symbols
1687 from 0 to 255 which "coincidentally" fit into one byte, and "utf8"
1688 strings actually consist of characters with values from 0 to
1689 0x10FFFF, not bytes, and when combining the two, it is illegal to
1690 treat either of these as bytes, but instead they must both be
1691 treated as numbers. To illustrate this, here is the behaviour of
1692 JSON contrasted with JSON::Create:
1693
1694 use utf8;
1695 use FindBin '$Bin';
1696 use JSON;
1697 use JSON::Create 'create_json';
1698 no utf8;
1699 my $x = 'γγγγγ';
1700 use utf8;
1701 my $y = 'γγγγγ';
1702 my $v = {x => $x, y => $y};
1703 print to_json ($v), "\n";
1704 print create_json ($v), "\n";
1705
1706 produces output
1707
1708 {"x":"Γ£ΒΒΓ£ΒΒΓ£ΒΒΓ£ΒΒΓ£ΒΒ","y":"γγγγγ"}
1709 {"x":"γγγγγ","y":"γγγγγ"}
1710
1711 (This example is included as examples/json-unicode.pl
1712 <https://fastapi.metacpan.org/source/BKB/JSON-
1713 Create-0.35/examples/json-unicode.pl> in the distribution.)
1714
1715 The Perl convention is that if a non-utf8 string and a utf8 string
1716 are combined, they should be combined as JSON does it, by treating
1717 each byte of the non-utf8 string as if it is a single Unicode code
1718 point, and writing equivalent UTF-8 bytes for that code point into
1719 the output. JSON::Create does a different thing, which is to insist
1720 that all input strings must be valid UTF-8, and after validating
1721 them, it combines them with the "utf8" strings without altering
1722 their contents. This break with the Perl convention is by design.
1723
1724 This example illustrates what happens with non-UTF-8 bytes:
1725
1726 use JSON;
1727 use JSON::Create 'create_json';
1728 use Gzip::Faster;
1729 $|=1;
1730 # Generate some random garbage bytes
1731 my $x = gzip ('γγγγγ');
1732 use utf8;
1733 my $y = 'γγγγγ';
1734 my $v = {x => $x, y => $y};
1735 print to_json ($v), "\n";
1736 print create_json ($v), "\n";
1737
1738 produces output
1739
1740 {"x":"\u001fΒ\b\u0000\u0000\u0000\u0000\u0000\u0000\u0003{ΓΓΓ½ΒΈΒ±Γ·qcΓΏΓ£ΓΒΒ\u001b'\u0003\u0000Β£ Β³\u0012\u000f\u0000\u0000\u0000","y":"γγγγγ"}
1741 Invalid UTF-8 at /usr/home/ben/projects/json-create/blib/lib/JSON/Create.pm line 192.
1742 Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/json-unicode-gzip-bytes.pl line 15.
1743
1744 (This example is included as examples/json-unicode-gzip-bytes.pl
1745 <https://fastapi.metacpan.org/source/BKB/JSON-
1746 Create-0.35/examples/json-unicode-gzip-bytes.pl> in the
1747 distribution.)
1748
1749 Using replace_bad_utf8 may cause a utf8 upgrade
1750 Please see the discussion under "replace_bad_utf8".
1751
1752 UTF-8 validation of user-supplied JSON
1753 If you supply JSON via a user routine such as "obj_handler", and
1754 you choose not to validate your output with "validate", and the
1755 input contains a character string ("utf8"), and you do not choose
1756 "downgrade_utf8", the entire output string has to be validated as
1757 UTF-8, to prevent a loophole where a string containing non-UTF-8
1758 compliant bytes could get upgraded to a character string ("utf8").
1759
1760 In this case, if invalid UTF-8 is detected, the diagnostic "Invalid
1761 UTF-8 from user routine" is printed, and the undefined value
1762 returned. Since the check is applied to the final output JSON,
1763 there is no information about which routine was at fault, so to get
1764 a more specific diagnosis, please switch on "validate".
1765
1766 Here is an example of how this may occur:
1767
1768 use JSON::Create;
1769 my $jc = JSON::Create->new ();
1770 # This type handler returns a non-UTF-8 string.
1771 $jc->type_handler (sub {return '"'. pack ("CCC", 0x99, 0x10, 0x0) . '"';});
1772 use utf8;
1773 # sub {1} triggers the type handler for a code reference, and the γΆγΌ
1774 # contains a "utf8" flag, so this combination sets off the problem.
1775 print $jc->run ({a => sub {1}, b => 'γΆγΌ'});
1776
1777 produces output
1778
1779 Invalid UTF-8 from user routine at /usr/home/ben/projects/json-create/examples/user-bad-utf8.pl line 11.
1780 Use of uninitialized value in print at /usr/home/ben/projects/json-create/examples/user-bad-utf8.pl line 11.
1781
1782 (This example is included as examples/user-bad-utf8.pl
1783 <https://fastapi.metacpan.org/source/BKB/JSON-
1784 Create-0.35/examples/user-bad-utf8.pl> in the distribution.)
1785
1787 All diagnostics are warnings by default. This behaviour can be altered
1788 with the method "fatal_errors".
1789
1790 Input's type cannot be serialized to JSON
1791 (Warning) A reference type such as a code reference, regexp, or
1792 glob was found in the user's input. For a discussion, see "Code,
1793 regexes, and other references". For how to overcome this, see
1794 "type_handler".
1795
1796 Invalid UTF-8
1797 (Warning) Bytes in a Perl string were not valid UTF-8. This
1798 behaviour can be altered with the method "replace_bad_utf8".
1799
1800 Invalid UTF-8 from user routine
1801 (Warning) A return value from a user routine was not valid UTF-8.
1802 See "UTF-8 validation of user-supplied JSON".
1803
1804 This diagnostic and the corresponding validation of user-supplied
1805 JSON was added in version 0.19 of the module.
1806
1807 JSON::Parse::assert_valid_json failed
1808 (Warning) The user requested validation with "validate" and this
1809 failed.
1810
1811 Non-ASCII byte in non-utf8 string
1812 (Warning) The user tried to encode a string containing a non-ASCII
1813 byte in a non-"utf8" string. This diagnostic occurs with either
1814 "create_json_strict" or "strict".
1815
1816 This diagnostic was added in version 0.20 of the module together
1817 with "create_json_strict" and the "strict" method.
1818
1819 Non-finite number in input
1820 (Warning) A number which cannot be represented as a floating point
1821 number was found in the input. See "Floating point numbers".
1822
1823 This diagnostic was added in version 0.20 of the module together
1824 with "create_json_strict" and the "strict" method.
1825
1826 Object cannot be serialized to JSON
1827 (Warning) An object in the input could not be serialized to JSON.
1828 See "Objects" for a discussion.
1829
1830 This diagnostic was added in version 0.20 of the module together
1831 with "create_json_strict" and the "strict" method.
1832
1833 Undefined value from user routine
1834 (Warning) An undefined value was returned by a user routine set
1835 with either "obj", "obj_handler", "type_handler" or
1836 "non_finite_handler".
1837
1839 There is a benchmarking script in bench/bench.pl which compares the
1840 performance of the module with JSON::XS and Cpanel::JSON::XS. Outputs
1841 look like this, where the "improve" column is the improvement in speed
1842 of the fastest module compared to the slowest:
1843
1844 Versions used:
1845 +-----+------------------+---------+
1846 | CJX | Cpanel::JSON::XS | 4.25 |
1847 +-----+------------------+---------+
1848 | JX | JSON::XS | 4.03 |
1849 +-----+------------------+---------+
1850 | JC | JSON::Create | 0.29_02 |
1851 +-----+------------------+---------+
1852 Comparing hash of ASCII strings...
1853
1854 Repetitions: 1000 x 200 = 200000
1855 +--------+--------+------------+---------+
1856 | Module | 1/min | min | improve |
1857 +--------+--------+------------+---------+
1858 | CJX | 380539 | 0.00262785 | 1 |
1859 | JC | 755322 | 0.00132394 | 1.98487 |
1860 | JX | 672056 | 0.00148797 | 1.76606 |
1861 +--------+--------+------------+---------+
1862
1863 Comparing hash of integers...
1864
1865 Repetitions: 1000 x 200 = 200000
1866 +--------+--------+------------+---------+
1867 | Module | 1/min | min | improve |
1868 +--------+--------+------------+---------+
1869 | CJX | 157604 | 0.00634503 | 1 |
1870 | JC | 388038 | 0.00257707 | 2.46211 |
1871 | JX | 199245 | 0.00501895 | 1.26422 |
1872 +--------+--------+------------+---------+
1873
1874 Comparing hash of Unicode strings...
1875
1876 Repetitions: 1000 x 200 = 200000
1877 +--------+-------------+-------------+---------+
1878 | Module | 1/min | min | improve |
1879 +--------+-------------+-------------+---------+
1880 | CJX | 513127 | 0.00194883 | 1 |
1881 | JC | 1.04831e+06 | 0.000953913 | 2.04299 |
1882 | JX | 808463 | 0.00123692 | 1.57556 |
1883 +--------+-------------+-------------+---------+
1884
1885 Comparing array of floats...
1886
1887 Repetitions: 1000 x 200 = 200000
1888 +--------+--------+------------+---------+
1889 | Module | 1/min | min | improve |
1890 +--------+--------+------------+---------+
1891 | CJX | 136707 | 0.00731492 | 1 |
1892 | JC | 342001 | 0.00292397 | 2.50171 |
1893 | JX | 156961 | 0.00637102 | 1.14816 |
1894 +--------+--------+------------+---------+
1895
1896 Comparing array of ASCII strings...
1897
1898 Repetitions: 1000 x 200 = 200000
1899 +--------+--------+------------+---------+
1900 | Module | 1/min | min | improve |
1901 +--------+--------+------------+---------+
1902 | CJX | 279881 | 0.00357294 | 1 |
1903 | JC | 547059 | 0.00182796 | 1.95461 |
1904 | JX | 487766 | 0.00205016 | 1.74276 |
1905 +--------+--------+------------+---------+
1906
1908 There is currently no way to delete object handlers set via "obj" from
1909 a JSON::Create object.
1910
1911 There are a few remaining undecided issues around the default object
1912 serialization.
1913
1914 No warning is printed when the user uses clashing methods like "bool"
1915 and "obj_handler".
1916
1917 There is a bug in JSON::Create::PP's handling of non-integer numbers.
1918
1919 The floating point printing loses precision on round trips.
1920
1922 "set_fformat" was added in version 0.07.
1923
1924 "validate" was added in version 0.07.
1925
1926 "fatal_errors" was added in version 0.10.
1927
1928 "replace_bad_utf8" was added in version 0.12.
1929
1930 "obj_handler" was added in version 0.13. This version also added
1931 loading of the Pure-Perl version of the module, JSON::Create::PP, if
1932 the loading of JSON::Create failed.
1933
1934 "non_finite_handler" was added in version 0.17.
1935
1936 "downgrade_utf8" was added in version 0.18.
1937
1938 The "Invalid UTF-8 from user routine" diagnostic was added in version
1939 0.19.
1940
1941 The "create_json_strict" function and "strict" methods and associated
1942 diagnostics were added in version 0.20.
1943
1944 Indentation was added for objects with "indent" in version 0.27.
1945
1946 Version 0.28 altered the handling of context-dependent variables to use
1947 the numerical part as a JSON number if valid, and the string part as a
1948 JSON string if not a valid number. See "Context-dependent variables"
1949 for all the details.
1950
1951 Arguments to "create_json" and "create_json_strict", and the methods
1952 "set", "sort" and "cmp" were added in version 0.29.
1953
1954 Version 0.30 rewrote "set" and related routines in XS and increased the
1955 speed of the module, and added "write_json".
1956
1957 In version 0.31, the method "run" was renamed "create".
1958
1959 Old names
1960 run The method "run" was renamed "create" in version 0.31. The old name
1961 is not deprecated and will continue to work indefinitely.
1962
1964 JSON::Create::PP
1965 This is a backup module for JSON::Create in pure Perl.
1966
1967 RFC 8259
1968 RFC 8259 "The JavaScript Object Notation (JSON) Data Interchange
1969 Format" <https://www.ietf.org/rfc/rfc8259.txt>
1970
1971 "SEE ALSO" in JSON::Parse
1972 Please refer to "SEE ALSO" in JSON::Parse for information on the
1973 specifications for JSON and a list of other CPAN modules for JSON.
1974
1975 Installing from the github repository
1976 Experimentally, it is possible to install this module from Github. You
1977 will also need to install Template and possibly some other modules.
1978
1979 Blog posts
1980 There are some blog posts about the JSON::Create internals of interest
1981 to Perl XS programmers here:
1982
1983 Using a user-defined sort order from XS
1984 <http://blogs.perl.org/users/ben_bullock/2020/12/alles-in-ordnung.html>
1985 The mysterious case of the SVt_PVIV
1986 <http://blogs.perl.org/users/ben_bullock/2020/11/the-mysterious-case-
1987 of-the-svt-pviv.html>
1988 JSON::Create now features indentation
1989 <http://blogs.perl.org/users/ben_bullock/2020/11/jsoncreate-now-
1990 features-indentation.html>
1991 av_fetch can return NULL
1992 <http://blogs.perl.org/users/ben_bullock/2020/02/av-fetch-can-return-
1993 null.html>
1994 Muddled numbers & strings <https://benbullock.substack.com/p/muddled-
1995 numbers-and-strings>
1996 This relates to the bug dealing with floating point and integer
1997 numbers found in version 0.33.
1998
2000 Ben Bullock, <bkb@cpan.org>
2001
2003 This package and associated files are copyright (C) 2015-2021 Ben
2004 Bullock.
2005
2006 You can use, copy, modify and redistribute this package and associated
2007 files under the Perl Artistic Licence or the GNU General Public
2008 Licence.
2009
2010 The sorting code used by "cmp" comes from the FreeBSD source code and
2011 is copyright by the Regents of the University of California.
2012
2013
2014
2015perl v5.36.0 2022-07-22 JSON::Create(3)