← Index
NYTProf Performance Profile   « line view »
For /home/ss5/perl5/perlbrew/perls/perl-5.22.0/bin/benchmarkanything-storage
  Run on Mon Jan 29 16:55:34 2018
Reported on Mon Jan 29 16:57:07 2018

Filename/home/ss5/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Cpanel/JSON/XS.pm
StatementsExecuted 14 statements in 790µs
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
10011110.9ms10.9msCpanel::JSON::XS::::decode Cpanel::JSON::XS::decode (xsub)
1000117.02ms7.02msCpanel::JSON::XS::::encode Cpanel::JSON::XS::encode (xsub)
1002112.07ms2.07msCpanel::JSON::XS::::new Cpanel::JSON::XS::new (xsub)
1001221.47ms1.47msCpanel::JSON::XS::::DESTROY Cpanel::JSON::XS::DESTROY (xsub)
11111µs39µsJSON::XS::Boolean::::BEGIN@1758JSON::XS::Boolean::BEGIN@1758
1119µs22µsCpanel::JSON::XS::::BEGIN@171 Cpanel::JSON::XS::BEGIN@171
1119µs88µsDynaLoader::::BEGIN@94 DynaLoader::BEGIN@94
1113µs3µsCpanel::JSON::XS::::BEGIN@172 Cpanel::JSON::XS::BEGIN@172
1113µs3µsCpanel::JSON::XS::::END Cpanel::JSON::XS::END (xsub)
2221µs1µsCpanel::JSON::XS::::utf8 Cpanel::JSON::XS::utf8 (xsub)
111300ns300nsCpanel::JSON::XS::::canonical Cpanel::JSON::XS::canonical (xsub)
0000s0sCpanel::JSON::XS::::false Cpanel::JSON::XS::false
0000s0sCpanel::JSON::XS::::from_json Cpanel::JSON::XS::from_json
0000s0sCpanel::JSON::XS::::is_bool Cpanel::JSON::XS::is_bool
0000s0sCpanel::JSON::XS::::to_json Cpanel::JSON::XS::to_json
0000s0sCpanel::JSON::XS::::true Cpanel::JSON::XS::true
0000s0sJSON::XS::Boolean::::__ANON__[:1758]JSON::XS::Boolean::__ANON__[:1758]
0000s0sJSON::XS::Boolean::::__ANON__[:1759]JSON::XS::Boolean::__ANON__[:1759]
0000s0sJSON::XS::Boolean::::__ANON__[:1760]JSON::XS::Boolean::__ANON__[:1760]
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
0188µsProfile data that couldn't be associated with a specific line:
# spent 88µs making 1 call to DynaLoader::BEGIN@94
1137µs=head1 NAME
2
3Cpanel::JSON::XS - JSON::XS for Cpanel, fast and correct serialising, also for 5.6.2
4
5=head1 SYNOPSIS
6
7 use Cpanel::JSON::XS;
8
9 # exported functions, they croak on error
10 # and expect/generate UTF-8
11
12 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
13 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
14
15 # OO-interface
16
17 $coder = Cpanel::JSON::XS->new->ascii->pretty->allow_nonref;
18 $pretty_printed_unencoded = $coder->encode ($perl_scalar);
19 $perl_scalar = $coder->decode ($unicode_json_text);
20
21 # Note that 5.6 misses most smart utf8 and encoding functionalities
22 # of newer releases.
23
24 # Note that L<JSON::MaybeXS> will automatically use Cpanel::JSON::XS
25 # if available, at virtually no speed overhead either, so you should
26 # be able to just:
27
28 use JSON::MaybeXS;
29
30 # and do the same things, except that you have a pure-perl fallback now.
31
32=head1 DESCRIPTION
33
34This module converts Perl data structures to JSON and vice versa. Its
35primary goal is to be I<correct> and its secondary goal is to be
36I<fast>. To reach the latter goal it was written in C.
37
38As this is the n-th-something JSON module on CPAN, what was the reason
39to write yet another JSON module? While it seems there are many JSON
40modules, none of them correctly handle all corner cases, and in most cases
41their maintainers are unresponsive, gone missing, or not listening to bug
42reports for other reasons.
43
44See below for the Cpanel fork.
45
46See MAPPING, below, on how Cpanel::JSON::XS maps perl values to JSON
47values and vice versa.
48
49=head2 FEATURES
50
51=over 4
52
53=item * correct Unicode handling
54
55This module knows how to handle Unicode with Perl version higher than 5.8.5,
56documents how and when it does so, and even documents what "correct" means.
57
58=item * round-trip integrity
59
60When you serialise a perl data structure using only data types supported
61by JSON and Perl, the deserialised data structure is identical on the Perl
62level. (e.g. the string "2.0" doesn't suddenly become "2" just because
63it looks like a number). There I<are> minor exceptions to this, read the
64MAPPING section below to learn about those.
65
66=item * strict checking of JSON correctness
67
68There is no guessing, no generating of illegal JSON texts by default,
69and only JSON is accepted as input by default (the latter is a security
70feature).
71
72=item * fast
73
74Compared to other JSON modules and other serialisers such as Storable,
75this module usually compares favourably in terms of speed, too.
76
77=item * simple to use
78
79This module has both a simple functional interface as well as an object
80oriented interface.
81
82=item * reasonably versatile output formats
83
84You can choose between the most compact guaranteed-single-line format
85possible (nice for simple line-based protocols), a pure-ASCII format
86(for when your transport is not 8-bit clean, still supports the whole
87Unicode range), or a pretty-printed format (for when you want to read that
88stuff). Or you can combine those features in whatever way you like.
89
90=back
91
92=head2 cPanel fork
93
94
# spent 88µs (9+79) within DynaLoader::BEGIN@94 which was called: # once (9µs+79µs) by XSLoader::load at line 0
Since the original author MLEHMANN has no public
95bugtracker, this cPanel fork sits now on github.
96
97src repo: L<https://github.com/rurban/Cpanel-JSON-XS>
98original: L<http://cvs.schmorp.de/JSON-XS/>
99
100RT: L<https://github.com/rurban/Cpanel-JSON-XS/issues>
101or L<https://rt.cpan.org/Public/Dist/Display.html?Queue=Cpanel-JSON-XS>
102
103B<Changes to JSON::XS>
104
105- fixed encode of numbers for dual-vars. Different string representations
106 are preserved, but numbers with temporary strings which represent the same number
107 are here treated as numbers, not strings. Cpanel::JSON::XS is a bit slower, but
108 preserves numeric types better.
109
110- different handling of inf/nan. Default now to null, optionally with -DSTRINGIFY_INFNAN
111 to "inf"/"nan".
112
113- added C<binary> extension, non-JSON and non JSON parsable, allows
114 C<\xNN> and C<\NNN> sequences.
115
116- 5.6.2 support; sacrificing some utf8 features (assuming bytes all-over),
117 no multi-byte unicode characters.
118
119- interop for true/false overloading. JSON::XS and JSON::PP representations
120 are accepted and JSON::XS accepts Cpanel::JSON::XS booleans [#13]
121
122- ithread support. Cpanel::JSON::XS is thread-safe, JSON::XS not
123
124- performance optimizations for threaded Perls
125
126- additional fixes for:
127
128 - [cpan #88061] AIX atof without USE_LONG_DOUBLE
129
130 - #10 unshare_hek crash
131
132 - #7 avoid re-blessing where possible (e.g. SvREADONLY restricted hashes)
133
134- public maintenance and bugtracker
135
136- use ppport.h, sanify XS.xs comment styles, harness C coding style
137
138- common::sense is optional. When available it is not used in the published
139 production module, just during development and testing.
140
141- extended testsuite
142
143
144=cut
145
146package Cpanel::JSON::XS;
147
1481200nsour $VERSION = '3.0115';
14914µsour @ISA = qw(Exporter);
150
1511400nsour @EXPORT = qw(encode_json decode_json to_json from_json);
152
153sub to_json($@) {
154 if ($] >= 5.008) {
155 require Carp;
156 Carp::croak ("Cpanel::JSON::XS::to_json has been renamed to encode_json, either downgrade to pre-2.0 versions of Cpanel::JSON::XS or rename the call");
157 } else {
158 _to_json(@_);
159 }
160}
161
162sub from_json($@) {
163 if ($] >= 5.008) {
164 require Carp;
165 Carp::croak ("Cpanel::JSON::XS::from_json has been renamed to decode_json, either downgrade to pre-2.0 versions of Cpanel::JSON::XS or rename the call");
166 } else {
167 _from_json(@_);
168 }
169}
170
171215µs235µs
# spent 22µs (9+13) within Cpanel::JSON::XS::BEGIN@171 which was called: # once (9µs+13µs) by JSON::MaybeXS::_choose_json_module at line 171
use Exporter;
# spent 22µs making 1 call to Cpanel::JSON::XS::BEGIN@171 # spent 13µs making 1 call to Exporter::import
1722528µs13µs
# spent 3µs within Cpanel::JSON::XS::BEGIN@172 which was called: # once (3µs+0s) by JSON::MaybeXS::_choose_json_module at line 172
use XSLoader;
# spent 3µs making 1 call to Cpanel::JSON::XS::BEGIN@172
173
174=head1 FUNCTIONAL INTERFACE
175
176The following convenience methods are provided by this module. They are
177exported by default:
178
179=over 4
180
181=item $json_text = encode_json $perl_scalar
182
183Converts the given Perl data structure to a UTF-8 encoded, binary string
184(that is, the string contains octets only). Croaks on error.
185
186This function call is functionally identical to:
187
188 $json_text = Cpanel::JSON::XS->new->utf8->encode ($perl_scalar)
189
190Except being faster.
191
192=item $perl_scalar = decode_json $json_text
193
194The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
195to parse that as an UTF-8 encoded JSON text, returning the resulting
196reference. Croaks on error.
197
198This function call is functionally identical to:
199
200 $perl_scalar = Cpanel::JSON::XS->new->utf8->decode ($json_text)
201
202Except being faster.
203
204=item $is_boolean = Cpanel::JSON::XS::is_bool $scalar
205
206Returns true if the passed scalar represents either C<JSON::XS::true> or
207C<JSON::XS::false>, two constants that act like C<1> and C<0>, respectively
208and are used to represent JSON C<true> and C<false> values in Perl.
209
210See MAPPING, below, for more information on how JSON values are mapped to
211Perl.
212
213=back
214
215=head1 DEPRECATED FUNCTIONS
216
217=over
218
219=item from_json
220
221from_json has been renamed to decode_json
222
223=item to_json
224
225to_json has been renamed to encode_json
226
227=back
228
229
230=head1 A FEW NOTES ON UNICODE AND PERL
231
232Since this often leads to confusion, here are a few very clear words on
233how Unicode works in Perl, modulo bugs.
234
235=over 4
236
237=item 1. Perl strings can store characters with ordinal values > 255.
238
239This enables you to store Unicode characters as single characters in a
240Perl string - very natural.
241
242=item 2. Perl does I<not> associate an encoding with your strings.
243
244... until you force it to, e.g. when matching it against a regex, or
245printing the scalar to a file, in which case Perl either interprets your
246string as locale-encoded text, octets/binary, or as Unicode, depending
247on various settings. In no case is an encoding stored together with your
248data, it is I<use> that decides encoding, not any magical meta data.
249
250=item 3. The internal utf-8 flag has no meaning with regards to the
251encoding of your string.
252
253=item 4. A "Unicode String" is simply a string where each character can be
254validly interpreted as a Unicode code point.
255
256If you have UTF-8 encoded data, it is no longer a Unicode string, but a
257Unicode string encoded in UTF-8, giving you a binary string.
258
259=item 5. A string containing "high" (> 255) character values is I<not> a UTF-8 string.
260
261=back
262
263I hope this helps :)
264
265
266=head1 OBJECT-ORIENTED INTERFACE
267
268The object oriented interface lets you configure your own encoding or
269decoding style, within the limits of supported formats.
270
271=over 4
272
273=item $json = new Cpanel::JSON::XS
274
275Creates a new JSON object that can be used to de/encode JSON
276strings. All boolean flags described below are by default I<disabled>.
277
278The mutators for flags all return the JSON object again and thus calls can
279be chained:
280
281 my $json = Cpanel::JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
282 => {"a": [1, 2]}
283
284=item $json = $json->ascii ([$enable])
285
286=item $enabled = $json->get_ascii
287
288If C<$enable> is true (or missing), then the C<encode> method will not
289generate characters outside the code range C<0..127> (which is ASCII). Any
290Unicode characters outside that range will be escaped using either a
291single C<\uXXXX> (BMP characters) or a double C<\uHHHH\uLLLLL> escape sequence,
292as per RFC4627. The resulting encoded JSON text can be treated as a native
293Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string,
294or any other superset of ASCII.
295
296If C<$enable> is false, then the C<encode> method will not escape Unicode
297characters unless required by the JSON syntax or other flags. This results
298in a faster and more compact format.
299
300See also the section I<ENCODING/CODESET FLAG NOTES> later in this
301document.
302
303The main use for this flag is to produce JSON texts that can be
304transmitted over a 7-bit channel, as the encoded JSON texts will not
305contain any 8 bit characters.
306
307 Cpanel::JSON::XS->new->ascii (1)->encode ([chr 0x10401])
308 => ["\ud801\udc01"]
309
310=item $json = $json->latin1 ([$enable])
311
312=item $enabled = $json->get_latin1
313
314If C<$enable> is true (or missing), then the C<encode> method will encode
315the resulting JSON text as latin1 (or iso-8859-1), escaping any characters
316outside the code range C<0..255>. The resulting string can be treated as a
317latin1-encoded JSON text or a native Unicode string. The C<decode> method
318will not be affected in any way by this flag, as C<decode> by default
319expects Unicode, which is a strict superset of latin1.
320
321If C<$enable> is false, then the C<encode> method will not escape Unicode
322characters unless required by the JSON syntax or other flags.
323
324See also the section I<ENCODING/CODESET FLAG NOTES> later in this
325document.
326
327The main use for this flag is efficiently encoding binary data as JSON
328text, as most octets will not be escaped, resulting in a smaller encoded
329size. The disadvantage is that the resulting JSON text is encoded
330in latin1 (and must correctly be treated as such when storing and
331transferring), a rare encoding for JSON. It is therefore most useful when
332you want to store data structures known to contain binary data efficiently
333in files or databases, not when talking to other JSON encoders/decoders.
334
335 Cpanel::JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
336 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
337
338=item $json = $json->binary ([$enable])
339
340=item $enabled = $json = $json->get_binary
341
342If the C<$enable> argument is true (or missing), then the C<encode>
343method will not try to detect an UTF-8 encoding in any JSON string, it
344will strictly interpret it as byte sequence. The result might contain
345new C<\xNN> sequences, which is B<unparsable JSON>. The C<decode> method
346forbids C<\uNNNN> sequences and accepts C<\xNN> and octal C<\NNN>
347sequences.
348
349There is also a special logic for perl 5.6 and utf8. 5.6 encodes any
350string to utf-8 automatically when seeing a codepoint >= C<0x80> and
351< C<0x100>. With the binary flag enabled decode the perl utf8 encoded
352string to the original byte encoding and encode this with C<\xNN>
353escapes. This will result to the same encodings as with newer
354perls. But note that binary multi-byte codepoints with 5.6 will
355result in C<illegal unicode character in binary string> errors,
356unlike with newer perls.
357
358If C<$enable> is false, then the C<encode> method will smartly try to
359detect Unicode characters unless required by the JSON syntax or other
360flags and hex and octal sequences are forbidden.
361
362See also the section I<ENCODING/CODESET FLAG NOTES> later in this
363document.
364
365The main use for this flag is to avoid the smart unicode detection and
366possible double encoding. The disadvantage is that the resulting JSON
367text is encoded in new C<\xNN> and in latin1 characters and must
368correctly be treated as such when storing and transferring, a rare
369encoding for JSON. It will produce non-readable JSON strings in the
370browser. It is therefore most useful when you want to store data
371structures known to contain binary data efficiently in files or
372databases, not when talking to other JSON encoders/decoders. The
373binary decoding method can also be used when an encoder produced a
374non-JSON conformant hex or octal encoding C<\xNN> or C<\NNN>.
375
376 Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{abc}"])
377 5.6: Error: malformed or illegal unicode character in binary string
378 >=5.8: ['\x89\xe0\xaa\xbc']
379
380 Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{bc}"])
381 => ["\x89\xbc"]
382
383 Cpanel::JSON::XS->new->binary->decode (["\x89\ua001"])
384 Error: malformed or illegal unicode character in binary string
385
386 Cpanel::JSON::XS->new->decode (["\x89"])
387 Error: illegal hex character in non-binary string
388
389=item $json = $json->utf8 ([$enable])
390
391=item $enabled = $json->get_utf8
392
393If C<$enable> is true (or missing), then the C<encode> method will encode
394the JSON result into UTF-8, as required by many protocols, while the
395C<decode> method expects to be handled an UTF-8-encoded string. Please
396note that UTF-8-encoded strings do not contain any characters outside the
397range C<0..255>, they are thus useful for bytewise/binary I/O. In future
398versions, enabling this option might enable autodetection of the UTF-16
399and UTF-32 encoding families, as described in RFC4627.
400
401If C<$enable> is false, then the C<encode> method will return the JSON
402string as a (non-encoded) Unicode string, while C<decode> expects thus a
403Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
404to be done yourself, e.g. using the Encode module.
405
406See also the section I<ENCODING/CODESET FLAG NOTES> later in this
407document.
408
409Example, output UTF-16BE-encoded JSON:
410
411 use Encode;
412 $jsontext = encode "UTF-16BE", Cpanel::JSON::XS->new->encode ($object);
413
414Example, decode UTF-32LE-encoded JSON:
415
416 use Encode;
417 $object = Cpanel::JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
418
419=item $json = $json->pretty ([$enable])
420
421This enables (or disables) all of the C<indent>, C<space_before> and
422C<space_after> (and in the future possibly more) flags in one call to
423generate the most readable (or most compact) form possible.
424
425Example, pretty-print some simple structure:
426
427 my $json = Cpanel::JSON::XS->new->pretty(1)->encode ({a => [1,2]})
428 =>
429 {
430 "a" : [
431 1,
432 2
433 ]
434 }
435
436=item $json = $json->indent ([$enable])
437
438=item $enabled = $json->get_indent
439
440If C<$enable> is true (or missing), then the C<encode> method will use a multiline
441format as output, putting every array member or object/hash key-value pair
442into its own line, indenting them properly.
443
444If C<$enable> is false, no newlines or indenting will be produced, and the
445resulting JSON text is guaranteed not to contain any C<newlines>.
446
447This setting has no effect when decoding JSON texts.
448
449=item $json = $json->space_before ([$enable])
450
451=item $enabled = $json->get_space_before
452
453If C<$enable> is true (or missing), then the C<encode> method will add an extra
454optional space before the C<:> separating keys from values in JSON objects.
455
456If C<$enable> is false, then the C<encode> method will not add any extra
457space at those places.
458
459This setting has no effect when decoding JSON texts. You will also
460most likely combine this setting with C<space_after>.
461
462Example, space_before enabled, space_after and indent disabled:
463
464 {"key" :"value"}
465
466=item $json = $json->space_after ([$enable])
467
468=item $enabled = $json->get_space_after
469
470If C<$enable> is true (or missing), then the C<encode> method will add an extra
471optional space after the C<:> separating keys from values in JSON objects
472and extra whitespace after the C<,> separating key-value pairs and array
473members.
474
475If C<$enable> is false, then the C<encode> method will not add any extra
476space at those places.
477
478This setting has no effect when decoding JSON texts.
479
480Example, space_before and indent disabled, space_after enabled:
481
482 {"key": "value"}
483
484=item $json = $json->relaxed ([$enable])
485
486=item $enabled = $json->get_relaxed
487
488If C<$enable> is true (or missing), then C<decode> will accept some
489extensions to normal JSON syntax (see below). C<encode> will not be
490affected in anyway. I<Be aware that this option makes you accept invalid
491JSON texts as if they were valid!>. I suggest only to use this option to
492parse application-specific files written by humans (configuration files,
493resource files etc.)
494
495If C<$enable> is false (the default), then C<decode> will only accept
496valid JSON texts.
497
498Currently accepted extensions are:
499
500=over 4
501
502=item * list items can have an end-comma
503
504JSON I<separates> array elements and key-value pairs with commas. This
505can be annoying if you write JSON texts manually and want to be able to
506quickly append elements, so this extension accepts comma at the end of
507such items not just between them:
508
509 [
510 1,
511 2, <- this comma not normally allowed
512 ]
513 {
514 "k1": "v1",
515 "k2": "v2", <- this comma not normally allowed
516 }
517
518=item * shell-style '#'-comments
519
520Whenever JSON allows whitespace, shell-style comments are additionally
521allowed. They are terminated by the first carriage-return or line-feed
522character, after which more white-space and comments are allowed.
523
524 [
525 1, # this comment not allowed in JSON
526 # neither this one...
527 ]
528
529=item * literal ASCII TAB characters in strings
530
531Literal ASCII TAB characters are now allowed in strings (and treated as
532C<\t>) in relaxed mode. Despite JSON mandates, that TAB character is
533substituted for "\t" sequence.
534
535 [
536 "Hello\tWorld",
537 "Hello<TAB>World", # literal <TAB> would not normally be allowed
538 ]
539
540=back
541
542=item $json = $json->canonical ([$enable])
543
544=item $enabled = $json->get_canonical
545
546If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
547by sorting their keys. This is adding a comparatively high overhead.
548
549If C<$enable> is false, then the C<encode> method will output key-value
550pairs in the order Perl stores them (which will likely change between runs
551of the same script, and can change even within the same run from 5.18
552onwards).
553
554This option is useful if you want the same data structure to be encoded as
555the same JSON text (given the same overall settings). If it is disabled,
556the same hash might be encoded differently even if contains the same data,
557as key-value pairs have no inherent ordering in Perl.
558
559This setting has no effect when decoding JSON texts.
560
561This setting has currently no effect on tied hashes.
562
563=item $json = $json->allow_nonref ([$enable])
564
565=item $enabled = $json->get_allow_nonref
566
567If C<$enable> is true (or missing), then the C<encode> method can convert a
568non-reference into its corresponding string, number or null JSON value,
569which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
570values instead of croaking.
571
572If C<$enable> is false, then the C<encode> method will croak if it isn't
573passed an arrayref or hashref, as JSON texts must either be an object
574or array. Likewise, C<decode> will croak if given something that is not a
575JSON object or array.
576
577Example, encode a Perl scalar as JSON value with enabled C<allow_nonref>,
578resulting in an invalid JSON text:
579
580 Cpanel::JSON::XS->new->allow_nonref->encode ("Hello, World!")
581 => "Hello, World!"
582
583=item $json = $json->allow_unknown ([$enable])
584
585=item $enabled = $json->get_allow_unknown
586
587If C<$enable> is true (or missing), then C<encode> will I<not> throw an
588exception when it encounters values it cannot represent in JSON (for
589example, filehandles) but instead will encode a JSON C<null> value. Note
590that blessed objects are not included here and are handled separately by
591c<allow_nonref>.
592
593If C<$enable> is false (the default), then C<encode> will throw an
594exception when it encounters anything it cannot encode as JSON.
595
596This option does not affect C<decode> in any way, and it is recommended to
597leave it off unless you know your communications partner.
598
599=item $json = $json->allow_blessed ([$enable])
600
601=item $enabled = $json->get_allow_blessed
602
603If C<$enable> is true (or missing), then the C<encode> method will not
604barf when it encounters a blessed reference. Instead, the value of the
605B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
606disabled or no C<TO_JSON> method found) or a representation of the
607object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
608encoded. Has no effect on C<decode>.
609
610If C<$enable> is false (the default), then C<encode> will throw an
611exception when it encounters a blessed object.
612
613This setting has no effect on C<decode>.
614
615=item $json = $json->convert_blessed ([$enable])
616
617=item $enabled = $json->get_convert_blessed
618
619If C<$enable> is true (or missing), then C<encode>, upon encountering a
620blessed object, will check for the availability of the C<TO_JSON> method
621on the object's class. If found, it will be called in scalar context
622and the resulting scalar will be encoded instead of the object. If no
623C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
624to do.
625
626The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
627returns other blessed objects, those will be handled in the same
628way. C<TO_JSON> must take care of not causing an endless recursion cycle
629(== crash) in this case. The name of C<TO_JSON> was chosen because other
630methods called by the Perl core (== not by the user of the object) are
631usually in upper case letters and to avoid collisions with any C<to_json>
632function or method.
633
634If C<$enable> is false (the default), then C<encode> will not consider
635this type of conversion.
636
637This setting has no effect on C<decode>.
638
639=item $json = $json->allow_tags ([$enable])
640
641=item $enabled = $json->get_allow_tags
642
643See L<OBJECT SERIALISATION> for details.
644
645If C<$enable> is true (or missing), then C<encode>, upon encountering a
646blessed object, will check for the availability of the C<FREEZE> method on
647the object's class. If found, it will be used to serialise the object into
648a nonstandard tagged JSON value (that JSON decoders cannot decode).
649
650It also causes C<decode> to parse such tagged JSON values and deserialise
651them via a call to the C<THAW> method.
652
653If C<$enable> is false (the default), then C<encode> will not consider
654this type of conversion, and tagged JSON values will cause a parse error
655in C<decode>, as if tags were not part of the grammar.
656
657=item $json = $json->filter_json_object ([$coderef->($hashref)])
658
659When C<$coderef> is specified, it will be called from C<decode> each
660time it decodes a JSON object. The only argument is a reference to the
661newly-created hash. If the code references returns a single scalar (which
662need not be a reference), this value (i.e. a copy of that scalar to avoid
663aliasing) is inserted into the deserialised data structure. If it returns
664an empty list (NOTE: I<not> C<undef>, which is a valid scalar), the
665original deserialised hash will be inserted. This setting can slow down
666decoding considerably.
667
668When C<$coderef> is omitted or undefined, any existing callback will
669be removed and C<decode> will not change the deserialised hash in any
670way.
671
672Example, convert all JSON objects into the integer 5:
673
674 my $js = Cpanel::JSON::XS->new->filter_json_object (sub { 5 });
675 # returns [5]
676 $js->decode ('[{}]')
677 # throw an exception because allow_nonref is not enabled
678 # so a lone 5 is not allowed.
679 $js->decode ('{"a":1, "b":2}');
680
681=item $json = $json->filter_json_single_key_object ($key [=> $coderef->($value)])
682
683Works remotely similar to C<filter_json_object>, but is only called for
684JSON objects having a single key named C<$key>.
685
686This C<$coderef> is called before the one specified via
687C<filter_json_object>, if any. It gets passed the single value in the JSON
688object. If it returns a single value, it will be inserted into the data
689structure. If it returns nothing (not even C<undef> but the empty list),
690the callback from C<filter_json_object> will be called next, as if no
691single-key callback were specified.
692
693If C<$coderef> is omitted or undefined, the corresponding callback will be
694disabled. There can only ever be one callback for a given key.
695
696As this callback gets called less often then the C<filter_json_object>
697one, decoding speed will not usually suffer as much. Therefore, single-key
698objects make excellent targets to serialise Perl objects into, especially
699as single-key JSON objects are as close to the type-tagged value concept
700as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
701support this in any way, so you need to make sure your data never looks
702like a serialised Perl hash.
703
704Typical names for the single object key are C<__class_whatever__>, or
705C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
706things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
707with real hashes.
708
709Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
710into the corresponding C<< $WIDGET{<id>} >> object:
711
712 # return whatever is in $WIDGET{5}:
713 Cpanel::JSON::XS
714 ->new
715 ->filter_json_single_key_object (__widget__ => sub {
716 $WIDGET{ $_[0] }
717 })
718 ->decode ('{"__widget__": 5')
719
720 # this can be used with a TO_JSON method in some "widget" class
721 # for serialisation to json:
722 sub WidgetBase::TO_JSON {
723 my ($self) = @_;
724
725 unless ($self->{id}) {
726 $self->{id} = ..get..some..id..;
727 $WIDGET{$self->{id}} = $self;
728 }
729
730 { __widget__ => $self->{id} }
731 }
732
733=item $json = $json->shrink ([$enable])
734
735=item $enabled = $json->get_shrink
736
737Perl usually over-allocates memory a bit when allocating space for
738strings. This flag optionally resizes strings generated by either
739C<encode> or C<decode> to their minimum size possible. This can save
740memory when your JSON texts are either very very long or you have many
741short strings. It will also try to downgrade any strings to octet-form
742if possible: perl stores strings internally either in an encoding called
743UTF-X or in octet-form. The latter cannot store everything but uses less
744space in general (and some buggy Perl or C code might even rely on that
745internal representation being used).
746
747The actual definition of what shrink does might change in future versions,
748but it will always try to save space at the expense of time.
749
750If C<$enable> is true (or missing), the string returned by C<encode> will
751be shrunk-to-fit, while all strings generated by C<decode> will also be
752shrunk-to-fit.
753
754If C<$enable> is false, then the normal perl allocation algorithms are used.
755If you work with your data, then this is likely to be faster.
756
757In the future, this setting might control other things, such as converting
758strings that look like integers or floats into integers or floats
759internally (there is no difference on the Perl level), saving space.
760
761=item $json = $json->max_depth ([$maximum_nesting_depth])
762
763=item $max_depth = $json->get_max_depth
764
765Sets the maximum nesting level (default C<512>) accepted while encoding
766or decoding. If a higher nesting level is detected in JSON text or a Perl
767data structure, then the encoder and decoder will stop and croak at that
768point.
769
770Nesting level is defined by number of hash- or arrayrefs that the encoder
771needs to traverse to reach a given point or the number of C<{> or C<[>
772characters without their matching closing parenthesis crossed to reach a
773given character in a string.
774
775Setting the maximum depth to one disallows any nesting, so that ensures
776that the object is only a single hash/object or array.
777
778If no argument is given, the highest possible setting will be used, which
779is rarely useful.
780
781Note that nesting is implemented by recursion in C. The default value has
782been chosen to be as large as typical operating systems allow without
783crashing.
784
785See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
786
787=item $json = $json->max_size ([$maximum_string_size])
788
789=item $max_size = $json->get_max_size
790
791Set the maximum length a JSON text may have (in bytes) where decoding is
792being attempted. The default is C<0>, meaning no limit. When C<decode>
793is called on a string that is longer then this many bytes, it will not
794attempt to decode the string but throw an exception. This setting has no
795effect on C<encode> (yet).
796
797If no argument is given, the limit check will be deactivated (same as when
798C<0> is specified).
799
800See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
801
802=item $json->stringify_infnan ([$infnan_mode = 1])
803
804=item $infnan_mode = $json->get_stringify_infnan
805
806Get or set how Cpanel::JSON::XS encodes C<inf> or C<nan> for numeric
807values.
808
809C<null>: infnan_mode = 0. Similar to most JSON modules in other languages.
810
811stringified: infnan_mode = 1. As in Mojo::JSON.
812
813inf/nan: infnan_mode = 2. As in JSON::XS, and older releases. Produces invalid JSON.
814
815=item $json_text = $json->encode ($perl_scalar)
816
817Converts the given Perl data structure (a simple scalar or a reference
818to a hash or array) to its JSON representation. Simple scalars will be
819converted into JSON string or number sequences, while references to arrays
820become JSON arrays and references to hashes become JSON objects. Undefined
821Perl values (e.g. C<undef>) become JSON C<null> values. Neither C<true>
822nor C<false> values will be generated.
823
824=item $perl_scalar = $json->decode ($json_text)
825
826The opposite of C<encode>: expects a JSON text and tries to parse it,
827returning the resulting simple scalar or reference. Croaks on error.
828
829JSON numbers and strings become simple Perl scalars. JSON arrays become
830Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
831C<1>, C<false> becomes C<0> and C<null> becomes C<undef>.
832
833=item ($perl_scalar, $characters) = $json->decode_prefix ($json_text)
834
835This works like the C<decode> method, but instead of raising an exception
836when there is trailing garbage after the first JSON object, it will
837silently stop parsing there and return the number of characters consumed
838so far.
839
840This is useful if your JSON texts are not delimited by an outer protocol
841and you need to know where the JSON text ends.
842
843 Cpanel::JSON::XS->new->decode_prefix ("[1] the tail")
844 => ([], 3)
845
846=item $json->to_json ($perl_hash_or_arrayref)
847
848Deprecated method for perl 5.8 and newer. Use L<encode_json> instead.
849
850=item $json->from_json ($utf8_encoded_json_text)
851
852Deprecated method for perl 5.8 and newer. Use L<decode_json> instead.
853
854=back
855
856
857=head1 INCREMENTAL PARSING
858
859In some cases, there is the need for incremental parsing of JSON
860texts. While this module always has to keep both JSON text and resulting
861Perl data structure in memory at one time, it does allow you to parse a
862JSON stream incrementally. It does so by accumulating text until it has
863a full JSON object, which it then can decode. This process is similar to
864using C<decode_prefix> to see if a full JSON object is available, but
865is much more efficient (and can be implemented with a minimum of method
866calls).
867
868Cpanel::JSON::XS will only attempt to parse the JSON text once it is sure it
869has enough text to get a decisive result, using a very simple but
870truly incremental parser. This means that it sometimes won't stop as
871early as the full parser, for example, it doesn't detect mismatched
872parentheses. The only thing it guarantees is that it starts decoding as
873soon as a syntactically valid JSON text has been seen. This means you need
874to set resource limits (e.g. C<max_size>) to ensure the parser will stop
875parsing in the presence if syntax errors.
876
877The following methods implement this incremental parser.
878
879=over 4
880
881=item [void, scalar or list context] = $json->incr_parse ([$string])
882
883This is the central parsing function. It can both append new text and
884extract objects from the stream accumulated so far (both of these
885functions are optional).
886
887If C<$string> is given, then this string is appended to the already
888existing JSON fragment stored in the C<$json> object.
889
890After that, if the function is called in void context, it will simply
891return without doing anything further. This can be used to add more text
892in as many chunks as you want.
893
894If the method is called in scalar context, then it will try to extract
895exactly I<one> JSON object. If that is successful, it will return this
896object, otherwise it will return C<undef>. If there is a parse error,
897this method will croak just as C<decode> would do (one can then use
898C<incr_skip> to skip the erroneous part). This is the most common way of
899using the method.
900
901And finally, in list context, it will try to extract as many objects
902from the stream as it can find and return them, or the empty list
903otherwise. For this to work, there must be no separators between the JSON
904objects or arrays, instead they must be concatenated back-to-back. If
905an error occurs, an exception will be raised as in the scalar context
906case. Note that in this case, any previously-parsed JSON texts will be
907lost.
908
909Example: Parse some JSON arrays/objects in a given string and return
910them.
911
912 my @objs = Cpanel::JSON::XS->new->incr_parse ("[5][7][1,2]");
913
914=item $lvalue_string = $json->incr_text (>5.8 only)
915
916This method returns the currently stored JSON fragment as an lvalue, that
917is, you can manipulate it. This I<only> works when a preceding call to
918C<incr_parse> in I<scalar context> successfully returned an object, and
9192. only with Perl >= 5.8
920
921Under all other circumstances you must not call this function (I mean
922it. although in simple tests it might actually work, it I<will> fail
923under real world conditions). As a special exception, you can also
924call this method before having parsed anything.
925
926This function is useful in two cases: a) finding the trailing text after a
927JSON object or b) parsing multiple JSON objects separated by non-JSON text
928(such as commas).
929
930=item $json->incr_skip
931
932This will reset the state of the incremental parser and will remove
933the parsed text from the input buffer so far. This is useful after
934C<incr_parse> died, in which case the input buffer and incremental parser
935state is left unchanged, to skip the text parsed so far and to reset the
936parse state.
937
938The difference to C<incr_reset> is that only text until the parse error
939occurred is removed.
940
941=item $json->incr_reset
942
943This completely resets the incremental parser, that is, after this call,
944it will be as if the parser had never parsed anything.
945
946This is useful if you want to repeatedly parse JSON objects and want to
947ignore any trailing data, which means you have to reset the parser after
948each successful decode.
949
950=back
951
952=head2 LIMITATIONS
953
954All options that affect decoding are supported, except
955C<allow_nonref>. The reason for this is that it cannot be made to
956work sensibly: JSON objects and arrays are self-delimited, i.e. you can concatenate
957them back to back and still decode them perfectly. This does not hold true
958for JSON numbers, however.
959
960For example, is the string C<1> a single JSON number, or is it simply the
961start of C<12>? Or is C<12> a single JSON number, or the concatenation
962of C<1> and C<2>? In neither case you can tell, and this is why Cpanel::JSON::XS
963takes the conservative route and disallows this case.
964
965=head2 EXAMPLES
966
967Some examples will make all this clearer. First, a simple example that
968works similarly to C<decode_prefix>: We want to decode the JSON object at
969the start of a string and identify the portion after the JSON object:
970
971 my $text = "[1,2,3] hello";
972
973 my $json = new Cpanel::JSON::XS;
974
975 my $obj = $json->incr_parse ($text)
976 or die "expected JSON object or array at beginning of string";
977
978 my $tail = $json->incr_text;
979 # $tail now contains " hello"
980
981Easy, isn't it?
982
983Now for a more complicated example: Imagine a hypothetical protocol where
984you read some requests from a TCP stream, and each request is a JSON
985array, without any separation between them (in fact, it is often useful to
986use newlines as "separators", as these get interpreted as whitespace at
987the start of the JSON text, which makes it possible to test said protocol
988with C<telnet>...).
989
990Here is how you'd do it (it is trivial to write this in an event-based
991manner):
992
993 my $json = new Cpanel::JSON::XS;
994
995 # read some data from the socket
996 while (sysread $socket, my $buf, 4096) {
997
998 # split and decode as many requests as possible
999 for my $request ($json->incr_parse ($buf)) {
1000 # act on the $request
1001 }
1002 }
1003
1004Another complicated example: Assume you have a string with JSON objects
1005or arrays, all separated by (optional) comma characters (e.g. C<[1],[2],
1006[3]>). To parse them, we have to skip the commas between the JSON texts,
1007and here is where the lvalue-ness of C<incr_text> comes in useful:
1008
1009 my $text = "[1],[2], [3]";
1010 my $json = new Cpanel::JSON::XS;
1011
1012 # void context, so no parsing done
1013 $json->incr_parse ($text);
1014
1015 # now extract as many objects as possible. note the
1016 # use of scalar context so incr_text can be called.
1017 while (my $obj = $json->incr_parse) {
1018 # do something with $obj
1019
1020 # now skip the optional comma
1021 $json->incr_text =~ s/^ \s* , //x;
1022 }
1023
1024Now lets go for a very complex example: Assume that you have a gigantic
1025JSON array-of-objects, many gigabytes in size, and you want to parse it,
1026but you cannot load it into memory fully (this has actually happened in
1027the real world :).
1028
1029Well, you lost, you have to implement your own JSON parser. But Cpanel::JSON::XS
1030can still help you: You implement a (very simple) array parser and let
1031JSON decode the array elements, which are all full JSON objects on their
1032own (this wouldn't work if the array elements could be JSON numbers, for
1033example):
1034
1035 my $json = new Cpanel::JSON::XS;
1036
1037 # open the monster
1038 open my $fh, "<bigfile.json"
1039 or die "bigfile: $!";
1040
1041 # first parse the initial "["
1042 for (;;) {
1043 sysread $fh, my $buf, 65536
1044 or die "read error: $!";
1045 $json->incr_parse ($buf); # void context, so no parsing
1046
1047 # Exit the loop once we found and removed(!) the initial "[".
1048 # In essence, we are (ab-)using the $json object as a simple scalar
1049 # we append data to.
1050 last if $json->incr_text =~ s/^ \s* \[ //x;
1051 }
1052
1053 # now we have the skipped the initial "[", so continue
1054 # parsing all the elements.
1055 for (;;) {
1056 # in this loop we read data until we got a single JSON object
1057 for (;;) {
1058 if (my $obj = $json->incr_parse) {
1059 # do something with $obj
1060 last;
1061 }
1062
1063 # add more data
1064 sysread $fh, my $buf, 65536
1065 or die "read error: $!";
1066 $json->incr_parse ($buf); # void context, so no parsing
1067 }
1068
1069 # in this loop we read data until we either found and parsed the
1070 # separating "," between elements, or the final "]"
1071 for (;;) {
1072 # first skip whitespace
1073 $json->incr_text =~ s/^\s*//;
1074
1075 # if we find "]", we are done
1076 if ($json->incr_text =~ s/^\]//) {
1077 print "finished.\n";
1078 exit;
1079 }
1080
1081 # if we find ",", we can continue with the next element
1082 if ($json->incr_text =~ s/^,//) {
1083 last;
1084 }
1085
1086 # if we find anything else, we have a parse error!
1087 if (length $json->incr_text) {
1088 die "parse error near ", $json->incr_text;
1089 }
1090
1091 # else add more data
1092 sysread $fh, my $buf, 65536
1093 or die "read error: $!";
1094 $json->incr_parse ($buf); # void context, so no parsing
1095 }
1096
1097This is a complex example, but most of the complexity comes from the fact
1098that we are trying to be correct (bear with me if I am wrong, I never ran
1099the above example :).
1100
- -
1103=head1 MAPPING
1104
1105This section describes how Cpanel::JSON::XS maps Perl values to JSON values and
1106vice versa. These mappings are designed to "do the right thing" in most
1107circumstances automatically, preserving round-tripping characteristics
1108(what you put in comes out as something equivalent).
1109
1110For the more enlightened: note that in the following descriptions,
1111lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl>
1112refers to the abstract Perl language itself.
1113
1114
1115=head2 JSON -> PERL
1116
1117=over 4
1118
1119=item object
1120
1121A JSON object becomes a reference to a hash in Perl. No ordering of object
1122keys is preserved (JSON does not preserve object key ordering itself).
1123
1124=item array
1125
1126A JSON array becomes a reference to an array in Perl.
1127
1128=item string
1129
1130A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1131are represented by the same codepoints in the Perl string, so no manual
1132decoding is necessary.
1133
1134=item number
1135
1136A JSON number becomes either an integer, numeric (floating point) or
1137string scalar in perl, depending on its range and any fractional parts. On
1138the Perl level, there is no difference between those as Perl handles all
1139the conversion details, but an integer may take slightly less memory and
1140might represent more values exactly than floating point numbers.
1141
1142If the number consists of digits only, Cpanel::JSON::XS will try to represent
1143it as an integer value. If that fails, it will try to represent it as
1144a numeric (floating point) value if that is possible without loss of
1145precision. Otherwise it will preserve the number as a string value (in
1146which case you lose roundtripping ability, as the JSON number will be
1147re-encoded to a JSON string).
1148
1149Numbers containing a fractional or exponential part will always be
1150represented as numeric (floating point) values, possibly at a loss of
1151precision (in which case you might lose perfect roundtripping ability, but
1152the JSON number will still be re-encoded as a JSON number).
1153
1154Note that precision is not accuracy - binary floating point values
1155cannot represent most decimal fractions exactly, and when converting
1156from and to floating point, C<Cpanel::JSON::XS> only guarantees precision
1157up to but not including the least significant bit.
1158
1159=item true, false
1160
1161These JSON atoms become C<Cpanel::JSON::XS::true> and C<Cpanel::JSON::XS::false>,
1162respectively. They are overloaded to act almost exactly like the numbers
1163C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
1164the C<Cpanel::JSON::XS::is_bool> function.
1165
1166=item null
1167
1168A JSON null atom becomes C<undef> in Perl.
1169
1170=item shell-style comments (C<< # I<text> >>)
1171
1172As a nonstandard extension to the JSON syntax that is enabled by the
1173C<relaxed> setting, shell-style comments are allowed. They can start
1174anywhere outside strings and go till the end of the line.
1175
1176=item tagged values (C<< (I<tag>)I<value> >>).
1177
1178Another nonstandard extension to the JSON syntax, enabled with the
1179C<allow_tags> setting, are tagged values. In this implementation, the
1180I<tag> must be a perl package/class name encoded as a JSON string, and the
1181I<value> must be a JSON array encoding optional constructor arguments.
1182
1183See L<OBJECT SERIALISATION>, below, for details.
1184
1185=back
1186
1187
1188=head2 PERL -> JSON
1189
1190The mapping from Perl to JSON is slightly more difficult, as Perl is a
1191truly typeless language, so we can only guess which JSON type is meant by
1192a Perl value.
1193
1194=over 4
1195
1196=item hash references
1197
1198Perl hash references become JSON objects. As there is no inherent ordering
1199in hash keys (or JSON objects), they will usually be encoded in a
1200pseudo-random order that can change between runs of the same program but
1201stays generally the same within a single run of a program. Cpanel::JSON::XS can
1202optionally sort the hash keys (determined by the I<canonical> flag), so
1203the same datastructure will serialise to the same JSON text (given same
1204settings and version of Cpanel::JSON::XS), but this incurs a runtime overhead
1205and is only rarely useful, e.g. when you want to compare some JSON text
1206against another for equality.
1207
1208=item array references
1209
1210Perl array references become JSON arrays.
1211
1212=item other references
1213
1214Other unblessed references are generally not allowed and will cause an
1215exception to be thrown, except for references to the integers C<0> and
1216C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1217also use C<Cpanel::JSON::XS::false> and C<Cpanel::JSON::XS::true> to improve
1218readability.
1219
1220 encode_json [\0, Cpanel::JSON::XS::true] # yields [false,true]
1221
1222=item Cpanel::JSON::XS::true, Cpanel::JSON::XS::false
1223
1224These special values become JSON true and JSON false values,
1225respectively. You can also use C<\1> and C<\0> directly if you want.
1226
1227=item blessed objects
1228
1229Blessed objects are not directly representable in JSON, but
1230C<Cpanel::JSON::XS> allows various ways of handling objects. See
1231L<OBJECT SERIALISATION>, below, for details.
1232
1233See the C<allow_blessed> and C<convert_blessed> methods on various options on
1234how to deal with this: basically, you can choose between throwing an
1235exception, encoding the reference as if it weren't blessed, or provide
1236your own serialiser method.
1237
1238=item simple scalars
1239
1240Simple Perl scalars (any scalar that is not a reference) are the most
1241difficult objects to encode: Cpanel::JSON::XS will encode undefined scalars or inf/nan
1242as JSON C<null> values, scalars that have last been used in a string context
1243before encoding as JSON strings, and anything else as number value:
1244
1245 # dump as number
1246 encode_json [2] # yields [2]
1247 encode_json [-3.0e17] # yields [-3e+17]
1248 my $value = 5; encode_json [$value] # yields [5]
1249
1250 # used as string, but the two representations are for the same number
1251 print $value;
1252 encode_json [$value] # yields [5]
1253
1254 # used as different string (non-matching dual-var)
1255 my $str = '0 but true';
1256 my $num = 1 + $str;
1257 encode_json [$num, $str] # yields [1,"0 but true"]
1258
1259 # undef becomes null
1260 encode_json [undef] # yields [null]
1261
1262 # inf or nan becomes null, unless you answered
1263 # "Do you want to handle inf/nan as strings" with yes
1264 encode_json [9**9**9] # yields [null]
1265
1266You can force the type to be a JSON string by stringifying it:
1267
1268 my $x = 3.1; # some variable containing a number
1269 "$x"; # stringified
1270 $x .= ""; # another, more awkward way to stringify
1271 print $x; # perl does it for you, too, quite often
1272
1273You can force the type to be a JSON number by numifying it:
1274
1275 my $x = "3"; # some variable containing a string
1276 $x += 0; # numify it, ensuring it will be dumped as a number
1277 $x *= 1; # same thing, the choice is yours.
1278
1279Note that numerical precision has the same meaning as under Perl (so
1280binary to decimal conversion follows the same rules as in Perl, which
1281can differ to other languages). Also, your perl interpreter might expose
1282extensions to the floating point numbers of your platform, such as
1283infinities or NaN's - these cannot be represented in JSON, and thus
1284null is returned instead. Optionally you can configure it to stringify
1285inf and nan values.
1286
1287=back
1288
1289=head2 OBJECT SERIALISATION
1290
1291As JSON cannot directly represent Perl objects, you have to choose between
1292a pure JSON representation (without the ability to deserialise the object
1293automatically again), and a nonstandard extension to the JSON syntax,
1294tagged values.
1295
1296=head3 SERIALISATION
1297
1298What happens when C<Cpanel::JSON::XS> encounters a Perl object depends on the
1299C<allow_blessed>, C<convert_blessed> and C<allow_tags> settings, which are
1300used in this order:
1301
1302=over 4
1303
1304=item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method.
1305
1306In this case, C<Cpanel::JSON::XS> uses the L<Types::Serialiser> object
1307serialisation protocol to create a tagged JSON value, using a nonstandard
1308extension to the JSON syntax.
1309
1310This works by invoking the C<FREEZE> method on the object, with the first
1311argument being the object to serialise, and the second argument being the
1312constant string C<JSON> to distinguish it from other serialisers.
1313
1314The C<FREEZE> method can return any number of values (i.e. zero or
1315more). These values and the paclkage/classname of the object will then be
1316encoded as a tagged JSON value in the following format:
1317
1318 ("classname")[FREEZE return values...]
1319
1320e.g.:
1321
1322 ("URI")["http://www.google.com/"]
1323 ("MyDate")[2013,10,29]
1324 ("ImageData::JPEG")["Z3...VlCg=="]
1325
1326For example, the hypothetical C<My::Object> C<FREEZE> method might use the
1327objects C<type> and C<id> members to encode the object:
1328
1329 sub My::Object::FREEZE {
1330 my ($self, $serialiser) = @_;
1331
1332 ($self->{type}, $self->{id})
1333 }
1334
1335=item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method.
1336
1337In this case, the C<TO_JSON> method of the object is invoked in scalar
1338context. It must return a single scalar that can be directly encoded into
1339JSON. This scalar replaces the object in the JSON text.
1340
1341For example, the following C<TO_JSON> method will convert all L<URI>
1342objects to JSON strings when serialised. The fatc that these values
1343originally were L<URI> objects is lost.
1344
1345 sub URI::TO_JSON {
1346 my ($uri) = @_;
1347 $uri->as_string
1348 }
1349
1350=item 3. C<allow_blessed> is enabled.
1351
1352The object will be serialised as a JSON null value.
1353
1354=item 4. none of the above
1355
1356If none of the settings are enabled or the respective methods are missing,
1357C<Cpanel::JSON::XS> throws an exception.
1358
1359=back
1360
1361=head3 DESERIALISATION
1362
1363For deserialisation there are only two cases to consider: either
1364nonstandard tagging was used, in which case C<allow_tags> decides,
1365or objects cannot be automatically be deserialised, in which
1366case you can use postprocessing or the C<filter_json_object> or
1367C<filter_json_single_key_object> callbacks to get some real objects our of
1368your JSON.
1369
1370This section only considers the tagged value case: I a tagged JSON object
1371is encountered during decoding and C<allow_tags> is disabled, a parse
1372error will result (as if tagged values were not part of the grammar).
1373
1374If C<allow_tags> is enabled, C<Cpanel::JSON::XS> will look up the C<THAW> method
1375of the package/classname used during serialisation (it will not attempt
1376to load the package as a Perl module). If there is no such method, the
1377decoding will fail with an error.
1378
1379Otherwise, the C<THAW> method is invoked with the classname as first
1380argument, the constant string C<JSON> as second argument, and all the
1381values from the JSON array (the values originally returned by the
1382C<FREEZE> method) as remaining arguments.
1383
1384The method must then return the object. While technically you can return
1385any Perl scalar, you might have to enable the C<enable_nonref> setting to
1386make that work in all cases, so better return an actual blessed reference.
1387
1388As an example, let's implement a C<THAW> function that regenerates the
1389C<My::Object> from the C<FREEZE> example earlier:
1390
1391 sub My::Object::THAW {
1392 my ($class, $serialiser, $type, $id) = @_;
1393
1394 $class->new (type => $type, id => $id)
1395 }
1396
1397
1398=head1 ENCODING/CODESET FLAG NOTES
1399
1400The interested reader might have seen a number of flags that signify
1401encodings or codesets - C<utf8>, C<latin1>, C<binary> and
1402C<ascii>. There seems to be some confusion on what these do, so here
1403is a short comparison:
1404
1405C<utf8> controls whether the JSON text created by C<encode> (and expected
1406by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only
1407control whether C<encode> escapes character values outside their respective
1408codeset range. Neither of these flags conflict with each other, although
1409some combinations make less sense than others.
1410
1411Care has been taken to make all flags symmetrical with respect to
1412C<encode> and C<decode>, that is, texts encoded with any combination of
1413these flag values will be correctly decoded when the same flags are used
1414- in general, if you use different flag settings while encoding vs. when
1415decoding you likely have a bug somewhere.
1416
1417Below comes a verbose discussion of these flags. Note that a "codeset" is
1418simply an abstract set of character-codepoint pairs, while an encoding
1419takes those codepoint numbers and I<encodes> them, in our case into
1420octets. Unicode is (among other things) a codeset, UTF-8 is an encoding,
1421and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at
1422the same time, which can be confusing.
1423
1424=over 4
1425
1426=item C<utf8> flag disabled
1427
1428When C<utf8> is disabled (the default), then C<encode>/C<decode> generate
1429and expect Unicode strings, that is, characters with high ordinal Unicode
1430values (> 255) will be encoded as such characters, and likewise such
1431characters are decoded as-is, no changes to them will be done, except
1432"(re-)interpreting" them as Unicode codepoints or Unicode characters,
1433respectively (to Perl, these are the same thing in strings unless you do
1434funny/weird/dumb stuff).
1435
1436This is useful when you want to do the encoding yourself (e.g. when you
1437want to have UTF-16 encoded JSON texts) or when some other layer does
1438the encoding for you (for example, when printing to a terminal using a
1439filehandle that transparently encodes to UTF-8 you certainly do NOT want
1440to UTF-8 encode your data first and have Perl encode it another time).
1441
1442=item C<utf8> flag enabled
1443
1444If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all
1445characters using the corresponding UTF-8 multi-byte sequence, and will
1446expect your input strings to be encoded as UTF-8, that is, no "character"
1447of the input string must have any value > 255, as UTF-8 does not allow
1448that.
1449
1450The C<utf8> flag therefore switches between two modes: disabled means you
1451will get a Unicode string in Perl, enabled means you get an UTF-8 encoded
1452octet/binary string in Perl.
1453
1454=item C<latin1>, C<binary> or C<ascii> flags enabled
1455
1456With C<latin1> (or C<ascii>) enabled, C<encode> will escape
1457characters with ordinal values > 255 (> 127 with C<ascii>) and encode
1458the remaining characters as specified by the C<utf8> flag.
1459With C<binary> enabled, ordinal values > 255 are illegal.
1460
1461If C<utf8> is disabled, then the result is also correctly encoded in those
1462character sets (as both are proper subsets of Unicode, meaning that a
1463Unicode string with all character values < 256 is the same thing as a
1464ISO-8859-1 string, and a Unicode string with all character values < 128 is
1465the same thing as an ASCII string in Perl).
1466
1467If C<utf8> is enabled, you still get a correct UTF-8-encoded string,
1468regardless of these flags, just some more characters will be escaped using
1469C<\uXXXX> then before.
1470
1471Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8
1472encoding, while ASCII-encoded strings are. That is because the ISO-8859-1
1473encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being
1474a subset of Unicode), while ASCII is.
1475
1476Surprisingly, C<decode> will ignore these flags and so treat all input
1477values as governed by the C<utf8> flag. If it is disabled, this allows you
1478to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of
1479Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.
1480
1481So neither C<latin1>, C<binary> nor C<ascii> are incompatible with the
1482C<utf8> flag - they only govern when the JSON output engine escapes a
1483character or not.
1484
1485The main use for C<latin1> or C<binary> is to relatively efficiently
1486store binary data as JSON, at the expense of breaking compatibility
1487with most JSON decoders.
1488
1489The main use for C<ascii> is to force the output to not contain characters
1490with values > 127, which means you can interpret the resulting string
1491as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and
14928-bit-encoding, and still get the same data structure back. This is useful
1493when your channel for JSON transfer is not 8-bit clean or the encoding
1494might be mangled in between (e.g. in mail), and works because ASCII is a
1495proper subset of most 8-bit and multibyte encodings in use in the world.
1496
1497=back
1498
1499
1500=head2 JSON and ECMAscript
1501
1502JSON syntax is based on how literals are represented in javascript (the
1503not-standardised predecessor of ECMAscript) which is presumably why it is
1504called "JavaScript Object Notation".
1505
1506However, JSON is not a subset (and also not a superset of course) of
1507ECMAscript (the standard) or javascript (whatever browsers actually
1508implement).
1509
1510If you want to use javascript's C<eval> function to "parse" JSON, you
1511might run into parse errors for valid JSON texts, or the resulting data
1512structure might not be queryable:
1513
1514One of the problems is that U+2028 and U+2029 are valid characters inside
1515JSON strings, but are not allowed in ECMAscript string literals, so the
1516following Perl fragment will not output something that can be guaranteed
1517to be parsable by javascript's C<eval>:
1518
1519 use Cpanel::JSON::XS;
1520
1521 print encode_json [chr 0x2028];
1522
1523The right fix for this is to use a proper JSON parser in your javascript
1524programs, and not rely on C<eval> (see for example Douglas Crockford's
1525F<json2.js> parser).
1526
1527If this is not an option, you can, as a stop-gap measure, simply encode to
1528ASCII-only JSON:
1529
1530 use Cpanel::JSON::XS;
1531
1532 print Cpanel::JSON::XS->new->ascii->encode ([chr 0x2028]);
1533
1534Note that this will enlarge the resulting JSON text quite a bit if you
1535have many non-ASCII characters. You might be tempted to run some regexes
1536to only escape U+2028 and U+2029, e.g.:
1537
1538 # DO NOT USE THIS!
1539 my $json = Cpanel::JSON::XS->new->utf8->encode ([chr 0x2028]);
1540 $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028
1541 $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029
1542 print $json;
1543
1544Note that I<this is a bad idea>: the above only works for U+2028 and
1545U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing
1546javascript implementations, however, have issues with other characters as
1547well - using C<eval> naively simply I<will> cause problems.
1548
1549Another problem is that some javascript implementations reserve
1550some property names for their own purposes (which probably makes
1551them non-ECMAscript-compliant). For example, Iceweasel reserves the
1552C<__proto__> property name for its own purposes.
1553
1554If that is a problem, you could parse try to filter the resulting JSON
1555output for these property strings, e.g.:
1556
1557 $json =~ s/"__proto__"\s*:/"__proto__renamed":/g;
1558
1559This works because C<__proto__> is not valid outside of strings, so every
1560occurrence of C<"__proto__"\s*:> must be a string used as property name.
1561
1562If you know of other incompatibilities, please let me know.
1563
1564
1565=head2 JSON and YAML
1566
1567You often hear that JSON is a subset of YAML. I<in general, there is
1568no way to configure JSON::XS to output a data structure as valid YAML>
1569that works in all cases. If you really must use Cpanel::JSON::XS to
1570generate YAML, you should use this algorithm (subject to change in
1571future versions):
1572
1573 my $to_yaml = Cpanel::JSON::XS->new->utf8->space_after (1);
1574 my $yaml = $to_yaml->encode ($ref) . "\n";
1575
1576This will I<usually> generate JSON texts that also parse as valid
1577YAML.
1578
1579
1580=head2 SPEED
1581
1582It seems that JSON::XS is surprisingly fast, as shown in the following
1583tables. They have been generated with the help of the C<eg/bench> program
1584in the JSON::XS distribution, to make it easy to compare on your own
1585system.
1586
1587JSON::XS is with L<Data::MessagePack> and L<Sereal> one of the fastest
1588serializers, because JSON and JSON::XS do not support backrefs (no
1589graph structures), only trees. Storable supports backrefs,
1590i.e. graphs. Data::MessagePack encodes its data binary (as Storable)
1591and supports only very simple subset of JSON.
1592
1593First comes a comparison between various modules using
1594a very short single-line JSON string (also available at
1595L<http://dist.schmorp.de/misc/json/short.json>).
1596
1597 {"method": "handleMessage", "params": ["user1",
1598 "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7,
1599 1, 0]}
1600
1601It shows the number of encodes/decodes per second (JSON::XS uses
1602the functional interface, while Cpanel::JSON::XS/2 uses the OO interface
1603with pretty-printing and hashkey sorting enabled, Cpanel::JSON::XS/3 enables
1604shrink. JSON::DWIW/DS uses the deserialise function, while JSON::DWIW::FJ
1605uses the from_json method). Higher is better:
1606
1607 module | encode | decode |
1608 --------------|------------|------------|
1609 JSON::DWIW/DS | 86302.551 | 102300.098 |
1610 JSON::DWIW/FJ | 86302.551 | 75983.768 |
1611 JSON::PP | 15827.562 | 6638.658 |
1612 JSON::Syck | 63358.066 | 47662.545 |
1613 JSON::XS | 511500.488 | 511500.488 |
1614 JSON::XS/2 | 291271.111 | 388361.481 |
1615 JSON::XS/3 | 361577.931 | 361577.931 |
1616 Storable | 66788.280 | 265462.278 |
1617 --------------+------------+------------+
1618
1619That is, JSON::XS is almost six times faster than JSON::DWIW on encoding,
1620about five times faster on decoding, and over thirty to seventy times
1621faster than JSON's pure perl implementation. It also compares favourably
1622to Storable for small amounts of data.
1623
1624Using a longer test string (roughly 18KB, generated from Yahoo! Locals
1625search API (L<http://dist.schmorp.de/misc/json/long.json>).
1626
1627 module | encode | decode |
1628 --------------|------------|------------|
1629 JSON::DWIW/DS | 1647.927 | 2673.916 |
1630 JSON::DWIW/FJ | 1630.249 | 2596.128 |
1631 JSON::PP | 400.640 | 62.311 |
1632 JSON::Syck | 1481.040 | 1524.869 |
1633 JSON::XS | 20661.596 | 9541.183 |
1634 JSON::XS/2 | 10683.403 | 9416.938 |
1635 JSON::XS/3 | 20661.596 | 9400.054 |
1636 Storable | 19765.806 | 10000.725 |
1637 --------------+------------+------------+
1638
1639Again, JSON::XS leads by far (except for Storable which non-surprisingly
1640decodes a bit faster).
1641
1642On large strings containing lots of high Unicode characters, some modules
1643(such as JSON::PC) seem to decode faster than JSON::XS, but the result
1644will be broken due to missing (or wrong) Unicode handling. Others refuse
1645to decode or encode properly, so it was impossible to prepare a fair
1646comparison table for that case.
1647
1648For updated graphs see L<https://github.com/Sereal/Sereal/wiki/Sereal-Comparison-Graphs>
1649
1650
1651=head1 INTEROP with JSON and JSON::XS
1652
1653JSON-XS-3.01 broke interoperability with JSON-2.90 with booleans. See L<JSON>.
1654
1655Cpanel::JSON::XS needs to know the JSON and JSON::XS versions to be able work
1656with those objects, especially when encoding a booleans like C<{"is_true":true}>.
1657So you need to load these modules before.
1658
1659true/false overloading is supported.
1660
1661JSON::XS and JSON::PP representations are accepted and older JSON::XS accepts
1662Cpanel::JSON::XS booleans.
1663
1664I cannot think of any reason to still use JSON::XS anymore.
1665
1666=head1 SECURITY CONSIDERATIONS
1667
1668When you are using JSON in a protocol, talking to untrusted potentially
1669hostile creatures requires relatively few measures.
1670
1671First of all, your JSON decoder should be secure, that is, should not have
1672any buffer overflows. Obviously, this module should ensure that.
1673
1674Second, you need to avoid resource-starving attacks. That means you should
1675limit the size of JSON texts you accept, or make sure then when your
1676resources run out, that's just fine (e.g. by using a separate process that
1677can crash safely). The size of a JSON text in octets or characters is
1678usually a good indication of the size of the resources required to decode
1679it into a Perl structure. While JSON::XS can check the size of the JSON
1680text, it might be too late when you already have it in memory, so you
1681might want to check the size before you accept the string.
1682
1683Third, Cpanel::JSON::XS recurses using the C stack when decoding objects and
1684arrays. The C stack is a limited resource: for instance, on my amd64
1685machine with 8MB of stack size I can decode around 180k nested arrays but
1686only 14k nested JSON objects (due to perl itself recursing deeply on croak
1687to free the temporary). If that is exceeded, the program crashes. To be
1688conservative, the default nesting limit is set to 512. If your process
1689has a smaller stack, you should adjust this setting accordingly with the
1690C<max_depth> method.
1691
1692Also keep in mind that Cpanel::JSON::XS might leak contents of your Perl data
1693structures in its error messages, so when you serialise sensitive
1694information you might want to make sure that exceptions thrown by JSON::XS
1695will not end up in front of untrusted eyes.
1696
1697If you are using Cpanel::JSON::XS to return packets to consumption
1698by JavaScript scripts in a browser you should have a look at
1699L<http://blog.archive.jpsykes.com/47/practical-csrf-and-json-security/> to
1700see whether you are vulnerable to some common attack vectors (which really
1701are browser design bugs, but it is still you who will have to deal with
1702it, as major browser developers care only for features, not about getting
1703security right). You might also want to also look at L<Mojo::JSON>
1704special escape rules to prevent from XSS attacks.
1705
1706=head1 THREADS
1707
1708Cpanel::JSON::XS has proper ithreads support, unlike JSON::XS. If you
1709encounter any bugs with thread support please report them.
1710
1711=head1 BUGS
1712
1713While the goal of the Cpanel::JSON::XS module is to be correct, that
1714unfortunately does not mean it's bug-free, only that the author thinks
1715its design is bug-free. If you keep reporting bugs they will be fixed
1716swiftly, though.
1717
1718Since the JSON::XS author refuses to use a public bugtracker and
1719prefers private emails, we've setup a tracker at RT, so you might want
1720to report any issues twice. Once in private to MLEHMANN to be fixed in
1721JSON::XS for the masses and one to our the public tracker. Issues
1722fixed by JSON::XS with a new release will also be backported to
1723Cpanel::JSON::XS and 5.6.2, as long as Cpanel relies on 5.6.2 and
1724Cpanel::JSON::XS as our serializer of choice.
1725
1726L<https://rt.cpan.org/Public/Dist/Display.html?Queue=Cpanel-JSON-XS>
1727
1728=head1 LICENSE
1729
1730This module is available under the same licences as perl, the Artistic
1731license and the GPL.
1732
1733=cut
1734
1735our ($true, $false);
17361400nsif ($INC{'JSON/XS.pm'} and $JSON::XS::VERSION ge "3.00") {
1737 $true = $Types::Serialiser::true; # readonly if loaded by JSON::XS
1738 $false = $Types::Serialiser::false;
1739} else {
17401700ns $true = do { bless \(my $dummy = 1), "JSON::XS::Boolean" };
17411400ns $false = do { bless \(my $dummy = 0), "JSON::XS::Boolean" };
1742}
1743
1744sub true() { $true }
1745sub false() { $false }
1746
1747sub is_bool($) {
1748 UNIVERSAL::isa($_[0], "JSON::XS::Boolean")
1749 or UNIVERSAL::isa($_[0], "JSON::PP::Boolean");
1750}
1751
17521162µs1296µsXSLoader::load 'Cpanel::JSON::XS', $VERSION;
# spent 296µs making 1 call to XSLoader::load
1753
1754package
1755 JSON::XS::Boolean;
1756
1757use overload
1758
# spent 39µs (11+28) within JSON::XS::Boolean::BEGIN@1758 which was called: # once (11µs+28µs) by JSON::MaybeXS::_choose_json_module at line 1771
"0+" => sub { ${$_[0]} },
1759 "++" => sub { $_[0] = ${$_[0]} + 1 },
1760 "--" => sub { $_[0] = ${$_[0]} - 1 },
1761 # '""' => sub { ${$_[0]} == 1 ? 'true' : 'false' },
1762 #'eq' => sub {
1763 # my ($obj, $op) = ref ($_[0]) ? ($_[0], $_[1]) : ($_[1], $_[0]);
1764 # if ($op eq 'true' or $op eq 'false') {
1765 # return "$obj" eq 'true' ? 'true' eq $op : 'false' eq $op;
1766 # }
1767 # else {
1768 # return $obj ? 1 == $op : 0 == $op;
1769 # }
1770 # },
1771228µs267µs fallback => 1;
# spent 39µs making 1 call to JSON::XS::Boolean::BEGIN@1758 # spent 28µs making 1 call to overload::import
1772
1773116µs1;
1774
1775=head1 SEE ALSO
1776
1777The F<cpanel_json_xs> command line utility for quick experiments.
1778
1779L<JSON>, L<JSON::XS>, L<JSON::MaybeXS>, L<Mojo::JSON>, L<Mojo::JSON::MaybeXS>,
1780L<JSON::SL>, L<JSON::DWIW>, L<JSON::YAJL>, L<https://metacpan.org/search?q=JSON>
1781
1782=head1 AUTHOR
1783
1784 Marc Lehmann <schmorp@schmorp.de>, http://home.schmorp.de/
1785
1786 cPanel Inc. <cpan@cpanel.net>
1787
1788=head1 MAINTAINER
1789
1790 cPanel Inc. <cpan@cpanel.net>
1791
1792=cut
1793
 
# spent 1.47ms within Cpanel::JSON::XS::DESTROY which was called 1001 times, avg 1µs/call: # 1000 times (1.46ms+0s) by BenchmarkAnything::Storage::Backend::SQL::add_single_benchmark at line 363 of BenchmarkAnything/Storage/Backend/SQL.pm, avg 1µs/call # once (2µs+0s) by main::_gc at line 434 of /home/ss5/perl5/perlbrew/perls/perl-5.22.0/bin/benchmarkanything-storage
sub Cpanel::JSON::XS::DESTROY; # xsub
# spent 3µs within Cpanel::JSON::XS::END which was called: # once (3µs+0s) by main::RUNTIME at line 0 of /home/ss5/perl5/perlbrew/perls/perl-5.22.0/bin/benchmarkanything-storage
sub Cpanel::JSON::XS::END; # xsub
# spent 300ns within Cpanel::JSON::XS::canonical which was called: # once (300ns+0s) by JSON::MaybeXS::new at line 47 of JSON/MaybeXS.pm
sub Cpanel::JSON::XS::canonical; # xsub
# spent 10.9ms within Cpanel::JSON::XS::decode which was called 1001 times, avg 11µs/call: # 1001 times (10.9ms+0s) by Search::Elasticsearch::Role::Serializer::JSON::try {...} at line 81 of Search/Elasticsearch/Role/Serializer/JSON.pm, avg 11µs/call
sub Cpanel::JSON::XS::decode; # xsub
# spent 7.02ms within Cpanel::JSON::XS::encode which was called 1000 times, avg 7µs/call: # 1000 times (7.02ms+0s) by Search::Elasticsearch::Role::Serializer::JSON::try {...} at line 24 of Search/Elasticsearch/Role/Serializer/JSON.pm, avg 7µs/call
sub Cpanel::JSON::XS::encode; # xsub
# spent 2.07ms within Cpanel::JSON::XS::new which was called 1002 times, avg 2µs/call: # 1002 times (2.07ms+0s) by JSON::MaybeXS::new at line 46 of JSON/MaybeXS.pm, avg 2µs/call
sub Cpanel::JSON::XS::new; # xsub
# spent 1µs within Cpanel::JSON::XS::utf8 which was called 2 times, avg 500ns/call: # once (600ns+0s) by Search::Elasticsearch::Serializer::JSON::__ANON__[/home/ss5/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/Search/Elasticsearch/Serializer/JSON.pm:6] at line 6 of Search/Elasticsearch/Serializer/JSON.pm # once (400ns+0s) by JSON::MaybeXS::new at line 47 of JSON/MaybeXS.pm
sub Cpanel::JSON::XS::utf8; # xsub