1XS(3) User Contributed Perl Documentation XS(3)
2
3
4
6 Cpanel::JSON::XS - cPanel fork of JSON::XS, fast and correct
7 serializing
8
10 use Cpanel::JSON::XS;
11
12 # exported functions, they croak on error
13 # and expect/generate UTF-8
14
15 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
16 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
17
18 # OO-interface
19
20 $coder = Cpanel::JSON::XS->new->ascii->pretty->allow_nonref;
21 $pretty_printed_unencoded = $coder->encode ($perl_scalar);
22 $perl_scalar = $coder->decode ($unicode_json_text);
23
24 # Note that 5.6 misses most smart utf8 and encoding functionalities
25 # of newer releases.
26
27 # Note that L<JSON::MaybeXS> will automatically use Cpanel::JSON::XS
28 # if available, at virtually no speed overhead either, so you should
29 # be able to just:
30
31 use JSON::MaybeXS;
32
33 # and do the same things, except that you have a pure-perl fallback now.
34
35 Note that this module will be replaced by a new JSON::Safe module soon,
36 with the same API just guaranteed safe defaults.
37
39 This module converts Perl data structures to JSON and vice versa. Its
40 primary goal is to be correct and its secondary goal is to be fast. To
41 reach the latter goal it was written in C.
42
43 As this is the n-th-something JSON module on CPAN, what was the reason
44 to write yet another JSON module? While it seems there are many JSON
45 modules, none of them correctly handle all corner cases, and in most
46 cases their maintainers are unresponsive, gone missing, or not
47 listening to bug reports for other reasons.
48
49 See below for the cPanel fork.
50
51 See MAPPING, below, on how Cpanel::JSON::XS maps perl values to JSON
52 values and vice versa.
53
54 FEATURES
55 • correct Unicode handling
56
57 This module knows how to handle Unicode with Perl version higher
58 than 5.8.5, documents how and when it does so, and even documents
59 what "correct" means.
60
61 • round-trip integrity
62
63 When you serialize a perl data structure using only data types
64 supported by JSON and Perl, the deserialized data structure is
65 identical on the Perl level. (e.g. the string "2.0" doesn't
66 suddenly become "2" just because it looks like a number). There are
67 minor exceptions to this, read the MAPPING section below to learn
68 about those.
69
70 • strict checking of JSON correctness
71
72 There is no guessing, no generating of illegal JSON texts by
73 default, and only JSON is accepted as input by default. the latter
74 is a security feature.
75
76 • fast
77
78 Compared to other JSON modules and other serializers such as
79 Storable, this module usually compares favourably in terms of
80 speed, too.
81
82 • simple to use
83
84 This module has both a simple functional interface as well as an
85 object oriented interface.
86
87 • reasonably versatile output formats
88
89 You can choose between the most compact guaranteed-single-line
90 format possible (nice for simple line-based protocols), a pure-
91 ASCII format (for when your transport is not 8-bit clean, still
92 supports the whole Unicode range), or a pretty-printed format (for
93 when you want to read that stuff). Or you can combine those
94 features in whatever way you like.
95
96 cPanel fork
97 Since the original author MLEHMANN has no public bugtracker, this
98 cPanel fork sits now on github.
99
100 src repo: <https://github.com/rurban/Cpanel-JSON-XS> original:
101 <http://cvs.schmorp.de/JSON-XS/>
102
103 RT: <https://github.com/rurban/Cpanel-JSON-XS/issues> or
104 <https://rt.cpan.org/Public/Dist/Display.html?Queue=Cpanel-JSON-XS>
105
106 Changes to JSON::XS
107
108 - stricter decode_json() as documented. non-refs are disallowed.
109 safe by default.
110 added a 2nd optional argument. decode() honors now allow_nonref.
111
112 - fixed encode of numbers for dual-vars. Different string
113 representations are preserved, but numbers with temporary strings
114 which represent the same number are here treated as numbers, not
115 strings. Cpanel::JSON::XS is a bit slower, but preserves numeric
116 types better.
117
118 - numbers ending with .0 stray numbers, are not converted to
119 integers. [#63] dual-vars which are represented as number not
120 integer (42+"bar" != 5.8.9) are now encoded as number (=> 42.0)
121 because internally it's now a NOK type. However !!1 which is
122 wrongly encoded in 5.8 as "1"/1.0 is still represented as integer.
123
124 - different handling of inf/nan. Default now to null, optionally with
125 stringify_infnan() to "inf"/"nan". [#28, #32]
126
127 - added "binary" extension, non-JSON and non JSON parsable, allows
128 "\xNN" and "\NNN" sequences.
129
130 - 5.6.2 support; sacrificing some utf8 features (assuming bytes
131 all-over), no multi-byte unicode characters with 5.6.
132
133 - interop for true/false overloading. JSON::XS, JSON::PP and Mojo::JSON
134 representations for booleans are accepted and JSON::XS accepts
135 Cpanel::JSON::XS booleans [#13, #37]
136 Fixed overloading of booleans. Cpanel::JSON::XS::true stringifies
137 again
138 to "1", not "true", analog to all other JSON modules.
139
140 - native boolean mapping of yes and no to true and false, as in
141 YAML::XS.
142 In perl "!0" is yes, "!1" is no.
143 The JSON value true maps to 1, false maps to 0. [#39]
144
145 - support arbitrary stringification with encode, with convert_blessed
146 and allow_blessed.
147
148 - ithread support. Cpanel::JSON::XS is thread-safe, JSON::XS not
149
150 - is_bool can be called as method, JSON::XS::is_bool not.
151
152 - performance optimizations for threaded Perls
153
154 - relaxed mode, allowing many popular extensions
155
156 - protect our magic object from corruption by wrong or missing external
157 methods, like FREEZE/THAW or serialization with other methods.
158
159 - additional fixes for:
160
161 - [cpan #88061] AIX atof without USE_LONG_DOUBLE
162
163 - #10 unshare_hek crash
164
165 - #7, #29 avoid re-blessing where possible. It fails in JSON::XS for
166 READONLY values, i.e. restricted hashes.
167
168 - #41 overloading of booleans, use the object not the reference.
169
170 - #62 -Dusequadmath conversion and no SEGV.
171
172 - #72 parsing of values followed \0, like 1\0 does fail.
173
174 - #72 parsing of illegal unicode or non-unicode characters.
175
176 - #96 locale-insensitive numeric conversion.
177
178 - #154 numeric conversion fixed since 5.22, using the same strtold as perl5.
179
180 - #167 sort tied hashes with canonical.
181
182 - public maintenance and bugtracker
183
184 - use ppport.h, sanify XS.xs comment styles, harness C coding style
185
186 - common::sense is optional. When available it is not used in the
187 published production module, just during development and testing.
188
189 - extended testsuite, passes all http://seriot.ch/parsing_json.html
190 tests. In fact it is the only know JSON decoder which does so,
191 while also being the fastest.
192
193 - support many more options and methods from JSON::PP:
194 stringify_infnan, allow_unknown, allow_stringify, allow_barekey,
195 encode_stringify, allow_bignum, allow_singlequote,
196 dupkeys_as_arrayref,
197 sort_by (partially), escape_slash, convert_blessed, ...
198 optional decode_json(, allow_nonref) arg.
199 relaxed implements allow_dupkeys.
200
201 - support all 5 unicode BOM's: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE,
202 UTF-32BE, encoding internally to UTF-8.
203
205 The following convenience methods are provided by this module. They are
206 exported by default:
207
208 $json_text = encode_json $perl_scalar, [json_type]
209 Converts the given Perl data structure to a UTF-8 encoded, binary
210 string (that is, the string contains octets only). Croaks on error.
211
212 This function call is functionally identical to:
213
214 $json_text = Cpanel::JSON::XS->new->utf8->encode ($perl_scalar, $json_type)
215
216 Except being faster.
217
218 For the type argument see Cpanel::JSON::XS::Type.
219
220 $perl_scalar = decode_json $json_text [, $allow_nonref [, my $json_type
221 ] ]
222 The opposite of "encode_json": expects an UTF-8 (binary) string of
223 an json reference and tries to parse that as an UTF-8 encoded JSON
224 text, returning the resulting reference. Croaks on error.
225
226 This function call is functionally identical to:
227
228 $perl_scalar = Cpanel::JSON::XS->new->utf8->decode ($json_text, $json_type)
229
230 except being faster.
231
232 Note that older decode_json versions in Cpanel::JSON::XS older than
233 3.0116 and JSON::XS did not set allow_nonref but allowed them due
234 to a bug in the decoder.
235
236 If the new 2nd optional $allow_nonref argument is set and not
237 false, the "allow_nonref" option will be set and the function will
238 act is described as in the relaxed RFC 7159 allowing all values
239 such as objects, arrays, strings, numbers, "null", "true", and
240 "false". See ""OLD" VS. "NEW" JSON (RFC 4627 VS. RFC 7159)" below,
241 why you don't want to do that.
242
243 For the 3rd optional type argument see Cpanel::JSON::XS::Type.
244
245 $is_boolean = Cpanel::JSON::XS::is_bool $scalar
246 Returns true if the passed scalar represents either
247 "JSON::PP::true" or "JSON::PP::false", two constants that act like
248 1 and 0, respectively and are used to represent JSON "true" and
249 "false" values in Perl. (Also recognizes the booleans produced by
250 JSON::XS.)
251
252 See MAPPING, below, for more information on how JSON values are
253 mapped to Perl.
254
256 from_json
257 from_json has been renamed to decode_json
258
259 to_json
260 to_json has been renamed to encode_json
261
263 Since this often leads to confusion, here are a few very clear words on
264 how Unicode works in Perl, modulo bugs.
265
266 1. Perl strings can store characters with ordinal values > 255.
267 This enables you to store Unicode characters as single characters
268 in a Perl string - very natural.
269
270 2. Perl does not associate an encoding with your strings.
271 ... until you force it to, e.g. when matching it against a regex,
272 or printing the scalar to a file, in which case Perl either
273 interprets your string as locale-encoded text, octets/binary, or as
274 Unicode, depending on various settings. In no case is an encoding
275 stored together with your data, it is use that decides encoding,
276 not any magical meta data.
277
278 3. The internal utf-8 flag has no meaning with regards to the encoding
279 of your string.
280 4. A "Unicode String" is simply a string where each character can be
281 validly interpreted as a Unicode code point.
282 If you have UTF-8 encoded data, it is no longer a Unicode string,
283 but a Unicode string encoded in UTF-8, giving you a binary string.
284
285 5. A string containing "high" (> 255) character values is not a UTF-8
286 string.
287 6. Unicode noncharacters only warn, as in core.
288 The 66 Unicode noncharacters U+FDD0..U+FDEF, and U+*FFFE, U+*FFFF
289 just warn, see <http://www.unicode.org/versions/corrigendum9.html>.
290 But illegal surrogate pairs fail to parse.
291
292 7. Raw non-Unicode characters above U+10FFFF are disallowed.
293 Raw non-Unicode characters outside the valid unicode range fail to
294 parse, because "A string is a sequence of zero or more Unicode
295 characters" RFC 7159 section 1 and "JSON text SHALL be encoded in
296 Unicode RFC 7159 section 8.1. We use now the UTF8_DISALLOW_SUPER
297 flag when parsing unicode.
298
299 I hope this helps :)
300
302 The object oriented interface lets you configure your own encoding or
303 decoding style, within the limits of supported formats.
304
305 $json = new Cpanel::JSON::XS
306 Creates a new JSON object that can be used to de/encode JSON
307 strings. All boolean flags described below are by default disabled.
308
309 The mutators for flags all return the JSON object again and thus
310 calls can be chained:
311
312 my $json = Cpanel::JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
313 => {"a": [1, 2]}
314
315 $json = $json->ascii ([$enable])
316 $enabled = $json->get_ascii
317 If $enable is true (or missing), then the "encode" method will not
318 generate characters outside the code range 0..127 (which is ASCII).
319 Any Unicode characters outside that range will be escaped using
320 either a single "\uXXXX" (BMP characters) or a double
321 "\uHHHH\uLLLLL" escape sequence, as per RFC4627. The resulting
322 encoded JSON text can be treated as a native Unicode string, an
323 ascii-encoded, latin1-encoded or UTF-8 encoded string, or any other
324 superset of ASCII.
325
326 If $enable is false, then the "encode" method will not escape
327 Unicode characters unless required by the JSON syntax or other
328 flags. This results in a faster and more compact format.
329
330 See also the section ENCODING/CODESET FLAG NOTES later in this
331 document.
332
333 The main use for this flag is to produce JSON texts that can be
334 transmitted over a 7-bit channel, as the encoded JSON texts will
335 not contain any 8 bit characters.
336
337 Cpanel::JSON::XS->new->ascii (1)->encode ([chr 0x10401])
338 => ["\ud801\udc01"]
339
340 $json = $json->latin1 ([$enable])
341 $enabled = $json->get_latin1
342 If $enable is true (or missing), then the "encode" method will
343 encode the resulting JSON text as latin1 (or ISO-8859-1), escaping
344 any characters outside the code range 0..255. The resulting string
345 can be treated as a latin1-encoded JSON text or a native Unicode
346 string. The "decode" method will not be affected in any way by this
347 flag, as "decode" by default expects Unicode, which is a strict
348 superset of latin1.
349
350 If $enable is false, then the "encode" method will not escape
351 Unicode characters unless required by the JSON syntax or other
352 flags.
353
354 See also the section ENCODING/CODESET FLAG NOTES later in this
355 document.
356
357 The main use for this flag is efficiently encoding binary data as
358 JSON text, as most octets will not be escaped, resulting in a
359 smaller encoded size. The disadvantage is that the resulting JSON
360 text is encoded in latin1 (and must correctly be treated as such
361 when storing and transferring), a rare encoding for JSON. It is
362 therefore most useful when you want to store data structures known
363 to contain binary data efficiently in files or databases, not when
364 talking to other JSON encoders/decoders.
365
366 Cpanel::JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
367 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
368
369 $json = $json->binary ([$enable])
370 $enabled = $json = $json->get_binary
371 If the $enable argument is true (or missing), then the "encode"
372 method will not try to detect an UTF-8 encoding in any JSON string,
373 it will strictly interpret it as byte sequence. The result might
374 contain new "\xNN" sequences, which is unparsable JSON. The
375 "decode" method forbids "\uNNNN" sequences and accepts "\xNN" and
376 octal "\NNN" sequences.
377
378 There is also a special logic for perl 5.6 and utf8. 5.6 encodes
379 any string to utf-8 automatically when seeing a codepoint >= 0x80
380 and < 0x100. With the binary flag enabled decode the perl utf8
381 encoded string to the original byte encoding and encode this with
382 "\xNN" escapes. This will result to the same encodings as with
383 newer perls. But note that binary multi-byte codepoints with 5.6
384 will result in "illegal unicode character in binary string" errors,
385 unlike with newer perls.
386
387 If $enable is false, then the "encode" method will smartly try to
388 detect Unicode characters unless required by the JSON syntax or
389 other flags and hex and octal sequences are forbidden.
390
391 See also the section ENCODING/CODESET FLAG NOTES later in this
392 document.
393
394 The main use for this flag is to avoid the smart unicode detection
395 and possible double encoding. The disadvantage is that the
396 resulting JSON text is encoded in new "\xNN" and in latin1
397 characters and must correctly be treated as such when storing and
398 transferring, a rare encoding for JSON. It will produce non-
399 readable JSON strings in the browser. It is therefore most useful
400 when you want to store data structures known to contain binary data
401 efficiently in files or databases, not when talking to other JSON
402 encoders/decoders. The binary decoding method can also be used
403 when an encoder produced a non-JSON conformant hex or octal
404 encoding "\xNN" or "\NNN".
405
406 Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{abc}"])
407 5.6: Error: malformed or illegal unicode character in binary string
408 >=5.8: ['\x89\xe0\xaa\xbc']
409
410 Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{bc}"])
411 => ["\x89\xbc"]
412
413 Cpanel::JSON::XS->new->binary->decode (["\x89\ua001"])
414 Error: malformed or illegal unicode character in binary string
415
416 Cpanel::JSON::XS->new->decode (["\x89"])
417 Error: illegal hex character in non-binary string
418
419 $json = $json->utf8 ([$enable])
420 $enabled = $json->get_utf8
421 If $enable is true (or missing), then the "encode" method will
422 encode the JSON result into UTF-8, as required by many protocols,
423 while the "decode" method expects to be handled an UTF-8-encoded
424 string. Please note that UTF-8-encoded strings do not contain any
425 characters outside the range 0..255, they are thus useful for
426 bytewise/binary I/O. In future versions, enabling this option might
427 enable autodetection of the UTF-16 and UTF-32 encoding families, as
428 described in RFC4627.
429
430 If $enable is false, then the "encode" method will return the JSON
431 string as a (non-encoded) Unicode string, while "decode" expects
432 thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or
433 UTF-16) needs to be done yourself, e.g. using the Encode module.
434
435 See also the section ENCODING/CODESET FLAG NOTES later in this
436 document.
437
438 Example, output UTF-16BE-encoded JSON:
439
440 use Encode;
441 $jsontext = encode "UTF-16BE", Cpanel::JSON::XS->new->encode ($object);
442
443 Example, decode UTF-32LE-encoded JSON:
444
445 use Encode;
446 $object = Cpanel::JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
447
448 $json = $json->pretty ([$enable])
449 This enables (or disables) all of the "indent", "space_before" and
450 "space_after" (and in the future possibly more) flags in one call
451 to generate the most readable (or most compact) form possible.
452
453 Example, pretty-print some simple structure:
454
455 my $json = Cpanel::JSON::XS->new->pretty(1)->encode ({a => [1,2]})
456 =>
457 {
458 "a" : [
459 1,
460 2
461 ]
462 }
463
464 $json = $json->indent ([$enable])
465 $enabled = $json->get_indent
466 If $enable is true (or missing), then the "encode" method will use
467 a multiline format as output, putting every array member or
468 object/hash key-value pair into its own line, indenting them
469 properly.
470
471 If $enable is false, no newlines or indenting will be produced, and
472 the resulting JSON text is guaranteed not to contain any
473 "newlines".
474
475 This setting has no effect when decoding JSON texts.
476
477 $json = $json->indent_length([$number_of_spaces])
478 $length = $json->get_indent_length()
479 Set the indent length (default 3). This option is only useful when
480 you also enable indent or pretty. The acceptable range is from 0
481 (no indentation) to 15
482
483 $json = $json->space_before ([$enable])
484 $enabled = $json->get_space_before
485 If $enable is true (or missing), then the "encode" method will add
486 an extra optional space before the ":" separating keys from values
487 in JSON objects.
488
489 If $enable is false, then the "encode" method will not add any
490 extra space at those places.
491
492 This setting has no effect when decoding JSON texts. You will also
493 most likely combine this setting with "space_after".
494
495 Example, space_before enabled, space_after and indent disabled:
496
497 {"key" :"value"}
498
499 $json = $json->space_after ([$enable])
500 $enabled = $json->get_space_after
501 If $enable is true (or missing), then the "encode" method will add
502 an extra optional space after the ":" separating keys from values
503 in JSON objects and extra whitespace after the "," separating key-
504 value pairs and array members.
505
506 If $enable is false, then the "encode" method will not add any
507 extra space at those places.
508
509 This setting has no effect when decoding JSON texts.
510
511 Example, space_before and indent disabled, space_after enabled:
512
513 {"key": "value"}
514
515 $json = $json->relaxed ([$enable])
516 $enabled = $json->get_relaxed
517 If $enable is true (or missing), then "decode" will accept some
518 extensions to normal JSON syntax (see below). "encode" will not be
519 affected in anyway. Be aware that this option makes you accept
520 invalid JSON texts as if they were valid!. I suggest only to use
521 this option to parse application-specific files written by humans
522 (configuration files, resource files etc.)
523
524 If $enable is false (the default), then "decode" will only accept
525 valid JSON texts.
526
527 Currently accepted extensions are:
528
529 • list items can have an end-comma
530
531 JSON separates array elements and key-value pairs with commas.
532 This can be annoying if you write JSON texts manually and want
533 to be able to quickly append elements, so this extension
534 accepts comma at the end of such items not just between them:
535
536 [
537 1,
538 2, <- this comma not normally allowed
539 ]
540 {
541 "k1": "v1",
542 "k2": "v2", <- this comma not normally allowed
543 }
544
545 • shell-style '#'-comments
546
547 Whenever JSON allows whitespace, shell-style comments are
548 additionally allowed. They are terminated by the first
549 carriage-return or line-feed character, after which more white-
550 space and comments are allowed.
551
552 [
553 1, # this comment not allowed in JSON
554 # neither this one...
555 ]
556
557 • literal ASCII TAB characters in strings
558
559 Literal ASCII TAB characters are now allowed in strings (and
560 treated as "\t") in relaxed mode. Despite JSON mandates, that
561 TAB character is substituted for "\t" sequence.
562
563 [
564 "Hello\tWorld",
565 "Hello<TAB>World", # literal <TAB> would not normally be allowed
566 ]
567
568 • allow_singlequote
569
570 Single quotes are accepted instead of double quotes. See the
571 "allow_singlequote" option.
572
573 { "foo":'bar' }
574 { 'foo':"bar" }
575 { 'foo':'bar' }
576
577 • allow_barekey
578
579 Accept unquoted object keys instead of with mandatory double
580 quotes. See the "allow_barekey" option.
581
582 { foo:"bar" }
583
584 • allow_dupkeys
585
586 Allow decoding of duplicate keys in hashes. By default
587 duplicate keys are forbidden. See
588 <http://seriot.ch/parsing_json.php#24>: RFC 7159 section 4:
589 "The names within an object should be unique." See the
590 "allow_dupkeys" option.
591
592 $json = $json->canonical ([$enable])
593 $enabled = $json->get_canonical
594 If $enable is true (or missing), then the "encode" method will
595 output JSON objects by sorting their keys. This is adding a
596 comparatively high overhead.
597
598 If $enable is false, then the "encode" method will output key-value
599 pairs in the order Perl stores them (which will likely change
600 between runs of the same script, and can change even within the
601 same run from 5.18 onwards).
602
603 This option is useful if you want the same data structure to be
604 encoded as the same JSON text (given the same overall settings). If
605 it is disabled, the same hash might be encoded differently even if
606 contains the same data, as key-value pairs have no inherent
607 ordering in Perl.
608
609 This setting has no effect when decoding JSON texts.
610
611 This is now also done with tied hashes, contrary to JSON::XS. But
612 note that with most large tied hashes stored as tree it is advised
613 to sort the iterator already and don't sort the hash output here.
614 Most such iterators are already sorted, as such e.g. DB_File with
615 "DB_BTREE".
616
617 $json = $json->sort_by (undef, 0, 1 or a block)
618 This currently only (un)sets the "canonical" option, and ignores
619 custom sort blocks.
620
621 This setting has no effect when decoding JSON texts.
622
623 This setting has currently no effect on tied hashes.
624
625 $json = $json->escape_slash ([$enable])
626 $enabled = $json->get_escape_slash
627 According to the JSON Grammar, the forward slash character (U+002F)
628 "/" need to be escaped. But by default strings are encoded without
629 escaping slashes in all perl JSON encoders.
630
631 If $enable is true (or missing), then "encode" will escape slashes,
632 "\/".
633
634 This setting has no effect when decoding JSON texts.
635
636 $json = $json->unblessed_bool ([$enable])
637 $enabled = $json->get_unblessed_bool
638 $json = $json->unblessed_bool([$enable])
639
640 If $enable is true (or missing), then "decode" will return Perl
641 non-object boolean variables (1 and 0) for JSON booleans ("true"
642 and "false"). If $enable is false, then "decode" will return
643 "JSON::PP::Boolean" objects for JSON booleans.
644
645 $json = $json->allow_singlequote ([$enable])
646 $enabled = $json->get_allow_singlequote
647 $json = $json->allow_singlequote([$enable])
648
649 If $enable is true (or missing), then "decode" will accept JSON
650 strings quoted by single quotations that are invalid JSON format.
651
652 $json->allow_singlequote->decode({"foo":'bar'});
653 $json->allow_singlequote->decode({'foo':"bar"});
654 $json->allow_singlequote->decode({'foo':'bar'});
655
656 This is also enabled with "relaxed". As same as the "relaxed"
657 option, this option may be used to parse application-specific files
658 written by humans.
659
660 $json = $json->allow_barekey ([$enable])
661 $enabled = $json->get_allow_barekey
662 $json = $json->allow_barekey([$enable])
663
664 If $enable is true (or missing), then "decode" will accept bare
665 keys of JSON object that are invalid JSON format.
666
667 Same as with the "relaxed" option, this option may be used to parse
668 application-specific files written by humans.
669
670 $json->allow_barekey->decode('{foo:"bar"}');
671
672 $json = $json->allow_bignum ([$enable])
673 $enabled = $json->get_allow_bignum
674 $json = $json->allow_bignum([$enable])
675
676 If $enable is true (or missing), then "decode" will convert the big
677 integer Perl cannot handle as integer into a Math::BigInt object
678 and convert a floating number (any) into a Math::BigFloat.
679
680 On the contrary, "encode" converts "Math::BigInt" objects and
681 "Math::BigFloat" objects into JSON numbers with "allow_blessed"
682 enable.
683
684 $json->allow_nonref->allow_blessed->allow_bignum;
685 $bigfloat = $json->decode('2.000000000000000000000000001');
686 print $json->encode($bigfloat);
687 # => 2.000000000000000000000000001
688
689 See "MAPPING" about the normal conversion of JSON number.
690
691 $json = $json->allow_bigint ([$enable])
692 This option is obsolete and replaced by allow_bignum.
693
694 $json = $json->allow_nonref ([$enable])
695 $enabled = $json->get_allow_nonref
696 If $enable is true (or missing), then the "encode" method can
697 convert a non-reference into its corresponding string, number or
698 null JSON value, which is an extension to RFC4627. Likewise,
699 "decode" will accept those JSON values instead of croaking.
700
701 If $enable is false, then the "encode" method will croak if it
702 isn't passed an arrayref or hashref, as JSON texts must either be
703 an object or array. Likewise, "decode" will croak if given
704 something that is not a JSON object or array.
705
706 Example, encode a Perl scalar as JSON value with enabled
707 "allow_nonref", resulting in an invalid JSON text:
708
709 Cpanel::JSON::XS->new->allow_nonref->encode ("Hello, World!")
710 => "Hello, World!"
711
712 $json = $json->allow_unknown ([$enable])
713 $enabled = $json->get_allow_unknown
714 If $enable is true (or missing), then "encode" will not throw an
715 exception when it encounters values it cannot represent in JSON
716 (for example, filehandles) but instead will encode a JSON "null"
717 value. Note that blessed objects are not included here and are
718 handled separately by c<allow_nonref>.
719
720 If $enable is false (the default), then "encode" will throw an
721 exception when it encounters anything it cannot encode as JSON.
722
723 This option does not affect "decode" in any way, and it is
724 recommended to leave it off unless you know your communications
725 partner.
726
727 $json = $json->allow_stringify ([$enable])
728 $enabled = $json->get_allow_stringify
729 If $enable is true (or missing), then "encode" will stringify the
730 non-object perl value or reference. Note that blessed objects are
731 not included here and are handled separately by "allow_blessed" and
732 "convert_blessed". String references are stringified to the string
733 value, other references as in perl.
734
735 This option does not affect "decode" in any way.
736
737 This option is special to this module, it is not supported by other
738 encoders. So it is not recommended to use it.
739
740 $json = $json->require_types ([$enable])
741 $enable = $json->get_require_types
742 $json = $json->require_types([$enable])
743
744 If $enable is true (or missing), then "encode" will require either
745 enabled "type_all_string" or second argument with supplied JSON
746 types. See Cpanel::JSON::XS::Type. When "type_all_string" is not
747 enabled or second argument is not provided (or is undef), then
748 "encode" croaks. It also croaks when the type for provided
749 structure in "encode" is incomplete.
750
751 $json = $json->type_all_string ([$enable])
752 $enable = $json->get_type_all_string
753 $json = $json->type_all_string([$enable])
754
755 If $enable is true (or missing), then "encode" will always produce
756 stable deterministic JSON string types in resulted output.
757
758 When $enable is false, then result of encoded JSON output may be
759 different for different Perl versions and may depends on loaded
760 modules.
761
762 This is useful it you need deterministic JSON types, independently
763 of used Perl version and other modules, but do not want to write
764 complicated type definitions for Cpanel::JSON::XS::Type.
765
766 $json = $json->allow_dupkeys ([$enable])
767 $enabled = $json->get_allow_dupkeys
768 If $enable is true (or missing), then the "decode" method will not
769 die when it encounters duplicate keys in a hash. "allow_dupkeys"
770 is also enabled in the "relaxed" mode.
771
772 The JSON spec allows duplicate name in objects but recommends to
773 disable it, however with Perl hashes they are impossible, parsing
774 JSON in Perl silently ignores duplicate names, using the last value
775 found.
776
777 See <http://seriot.ch/parsing_json.php#24>: RFC 7159 section 4:
778 "The names within an object should be unique."
779
780 $json = $json->dupkeys_as_arrayref ([$enable])
781 $enabled = $json->get_dupkeys_as_arrayref
782 If enabled, allow decoding of duplicate keys in hashes and store
783 the values as arrayref in the hash instead. By default duplicate
784 keys are forbidden. Enabling this also enables the "allow_dupkeys"
785 option, but disabling this does not disable the "allow_dupkeys"
786 option.
787
788 Example:
789
790 $json->dupkeys_as_arrayref;
791 print encode_json ($json->decode ('{"a":"b","a":"c"}'));
792
793 => {"a":["b","c"]}
794
795 This changes the result structure, thus cannot be enabled by
796 default. The client must be aware of it. The resulting arrayref is
797 not yet marked somehow (blessed or such).
798
799 $json = $json->allow_blessed ([$enable])
800 $enabled = $json->get_allow_blessed
801 If $enable is true (or missing), then the "encode" method will not
802 barf when it encounters a blessed reference. Instead, the value of
803 the convert_blessed option will decide whether "null"
804 ("convert_blessed" disabled or no "TO_JSON" method found) or a
805 representation of the object ("convert_blessed" enabled and
806 "TO_JSON" method found) is being encoded. Has no effect on
807 "decode".
808
809 If $enable is false (the default), then "encode" will throw an
810 exception when it encounters a blessed object without
811 "convert_blessed" and a "TO_JSON" method.
812
813 This setting has no effect on "decode".
814
815 $json = $json->convert_blessed ([$enable])
816 $enabled = $json->get_convert_blessed
817 If $enable is true (or missing), then "encode", upon encountering a
818 blessed object, will check for the availability of the "TO_JSON"
819 method on the object's class. If found, it will be called in scalar
820 context and the resulting scalar will be encoded instead of the
821 object. If no "TO_JSON" method is found, a stringification overload
822 method is tried next. If both are not found, the value of
823 "allow_blessed" will decide what to do.
824
825 The "TO_JSON" method may safely call die if it wants. If "TO_JSON"
826 returns other blessed objects, those will be handled in the same
827 way. "TO_JSON" must take care of not causing an endless recursion
828 cycle (== crash) in this case. The same care must be taken with
829 calling encode in stringify overloads (even if this works by luck
830 in older perls) or other callbacks. The name of "TO_JSON" was
831 chosen because other methods called by the Perl core (== not by the
832 user of the object) are usually in upper case letters and to avoid
833 collisions with any "to_json" function or method.
834
835 If $enable is false (the default), then "encode" will not consider
836 this type of conversion.
837
838 This setting has no effect on "decode".
839
840 $json = $json->allow_tags ([$enable])
841 $enabled = $json->get_allow_tags
842 See "OBJECT SERIALIZATION" for details.
843
844 If $enable is true (or missing), then "encode", upon encountering a
845 blessed object, will check for the availability of the "FREEZE"
846 method on the object's class. If found, it will be used to
847 serialize the object into a nonstandard tagged JSON value (that
848 JSON decoders cannot decode).
849
850 It also causes "decode" to parse such tagged JSON values and
851 deserialize them via a call to the "THAW" method.
852
853 If $enable is false (the default), then "encode" will not consider
854 this type of conversion, and tagged JSON values will cause a parse
855 error in "decode", as if tags were not part of the grammar.
856
857 $json = $json->filter_json_object ([$coderef->($hashref)])
858 When $coderef is specified, it will be called from "decode" each
859 time it decodes a JSON object. The only argument is a reference to
860 the newly-created hash. If the code references returns a single
861 scalar (which need not be a reference), this value (i.e. a copy of
862 that scalar to avoid aliasing) is inserted into the deserialized
863 data structure. If it returns an empty list (NOTE: not "undef",
864 which is a valid scalar), the original deserialized hash will be
865 inserted. This setting can slow down decoding considerably.
866
867 When $coderef is omitted or undefined, any existing callback will
868 be removed and "decode" will not change the deserialized hash in
869 any way.
870
871 Example, convert all JSON objects into the integer 5:
872
873 my $js = Cpanel::JSON::XS->new->filter_json_object (sub { 5 });
874 # returns [5]
875 $js->decode ('[{}]')
876 # throw an exception because allow_nonref is not enabled
877 # so a lone 5 is not allowed.
878 $js->decode ('{"a":1, "b":2}');
879
880 $json = $json->filter_json_single_key_object ($key [=>
881 $coderef->($value)])
882 Works remotely similar to "filter_json_object", but is only called
883 for JSON objects having a single key named $key.
884
885 This $coderef is called before the one specified via
886 "filter_json_object", if any. It gets passed the single value in
887 the JSON object. If it returns a single value, it will be inserted
888 into the data structure. If it returns nothing (not even "undef"
889 but the empty list), the callback from "filter_json_object" will be
890 called next, as if no single-key callback were specified.
891
892 If $coderef is omitted or undefined, the corresponding callback
893 will be disabled. There can only ever be one callback for a given
894 key.
895
896 As this callback gets called less often then the
897 "filter_json_object" one, decoding speed will not usually suffer as
898 much. Therefore, single-key objects make excellent targets to
899 serialize Perl objects into, especially as single-key JSON objects
900 are as close to the type-tagged value concept as JSON gets (it's
901 basically an ID/VALUE tuple). Of course, JSON does not support this
902 in any way, so you need to make sure your data never looks like a
903 serialized Perl hash.
904
905 Typical names for the single object key are "__class_whatever__",
906 or "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or
907 even things like "__class_md5sum(classname)__", to reduce the risk
908 of clashing with real hashes.
909
910 Example, decode JSON objects of the form "{ "__widget__" => <id> }"
911 into the corresponding $WIDGET{<id>} object:
912
913 # return whatever is in $WIDGET{5}:
914 Cpanel::JSON::XS
915 ->new
916 ->filter_json_single_key_object (__widget__ => sub {
917 $WIDGET{ $_[0] }
918 })
919 ->decode ('{"__widget__": 5')
920
921 # this can be used with a TO_JSON method in some "widget" class
922 # for serialization to json:
923 sub WidgetBase::TO_JSON {
924 my ($self) = @_;
925
926 unless ($self->{id}) {
927 $self->{id} = ..get..some..id..;
928 $WIDGET{$self->{id}} = $self;
929 }
930
931 { __widget__ => $self->{id} }
932 }
933
934 $json = $json->shrink ([$enable])
935 $enabled = $json->get_shrink
936 Perl usually over-allocates memory a bit when allocating space for
937 strings. This flag optionally resizes strings generated by either
938 "encode" or "decode" to their minimum size possible. This can save
939 memory when your JSON texts are either very very long or you have
940 many short strings. It will also try to downgrade any strings to
941 octet-form if possible: perl stores strings internally either in an
942 encoding called UTF-X or in octet-form. The latter cannot store
943 everything but uses less space in general (and some buggy Perl or C
944 code might even rely on that internal representation being used).
945
946 The actual definition of what shrink does might change in future
947 versions, but it will always try to save space at the expense of
948 time.
949
950 If $enable is true (or missing), the string returned by "encode"
951 will be shrunk-to-fit, while all strings generated by "decode" will
952 also be shrunk-to-fit.
953
954 If $enable is false, then the normal perl allocation algorithms are
955 used. If you work with your data, then this is likely to be
956 faster.
957
958 In the future, this setting might control other things, such as
959 converting strings that look like integers or floats into integers
960 or floats internally (there is no difference on the Perl level),
961 saving space.
962
963 $json = $json->max_depth ([$maximum_nesting_depth])
964 $max_depth = $json->get_max_depth
965 Sets the maximum nesting level (default 512) accepted while
966 encoding or decoding. If a higher nesting level is detected in JSON
967 text or a Perl data structure, then the encoder and decoder will
968 stop and croak at that point.
969
970 Nesting level is defined by number of hash- or arrayrefs that the
971 encoder needs to traverse to reach a given point or the number of
972 "{" or "[" characters without their matching closing parenthesis
973 crossed to reach a given character in a string.
974
975 Setting the maximum depth to one disallows any nesting, so that
976 ensures that the object is only a single hash/object or array.
977
978 If no argument is given, the highest possible setting will be used,
979 which is rarely useful.
980
981 Note that nesting is implemented by recursion in C. The default
982 value has been chosen to be as large as typical operating systems
983 allow without crashing.
984
985 See "SECURITY CONSIDERATIONS", below, for more info on why this is
986 useful.
987
988 $json = $json->max_size ([$maximum_string_size])
989 $max_size = $json->get_max_size
990 Set the maximum length a JSON text may have (in bytes) where
991 decoding is being attempted. The default is 0, meaning no limit.
992 When "decode" is called on a string that is longer then this many
993 bytes, it will not attempt to decode the string but throw an
994 exception. This setting has no effect on "encode" (yet).
995
996 If no argument is given, the limit check will be deactivated (same
997 as when 0 is specified).
998
999 See "SECURITY CONSIDERATIONS", below, for more info on why this is
1000 useful.
1001
1002 $json->stringify_infnan ([$infnan_mode = 1])
1003 $infnan_mode = $json->get_stringify_infnan
1004 Get or set how Cpanel::JSON::XS encodes "inf", "-inf" or "nan" for
1005 numeric values. Also qnan, snan or negative nan on some platforms.
1006
1007 "null": infnan_mode = 0. Similar to most JSON modules in other
1008 languages. Always null.
1009
1010 stringified: infnan_mode = 1. As in Mojo::JSON. Platform specific
1011 strings. Stringified via sprintf(%g), with double quotes.
1012
1013 inf/nan: infnan_mode = 2. As in JSON::XS, and older releases.
1014 Passes through platform dependent values, invalid JSON. Stringified
1015 via sprintf(%g), but without double quotes.
1016
1017 "inf/-inf/nan": infnan_mode = 3. Platform independent inf/nan/-inf
1018 strings. No QNAN/SNAN/negative NAN support, unified to "nan". Much
1019 easier to detect, but may conflict with valid strings.
1020
1021 $json_text = $json->encode ($perl_scalar, $json_type)
1022 Converts the given Perl data structure (a simple scalar or a
1023 reference to a hash or array) to its JSON representation. Simple
1024 scalars will be converted into JSON string or number sequences,
1025 while references to arrays become JSON arrays and references to
1026 hashes become JSON objects. Undefined Perl values (e.g. "undef")
1027 become JSON "null" values. Neither "true" nor "false" values will
1028 be generated.
1029
1030 For the type argument see Cpanel::JSON::XS::Type.
1031
1032 $perl_scalar = $json->decode ($json_text, my $json_type)
1033 The opposite of "encode": expects a JSON text and tries to parse
1034 it, returning the resulting simple scalar or reference. Croaks on
1035 error.
1036
1037 JSON numbers and strings become simple Perl scalars. JSON arrays
1038 become Perl arrayrefs and JSON objects become Perl hashrefs. "true"
1039 becomes 1, "false" becomes 0 and "null" becomes "undef".
1040
1041 For the type argument see Cpanel::JSON::XS::Type.
1042
1043 ($perl_scalar, $characters) = $json->decode_prefix ($json_text)
1044 This works like the "decode" method, but instead of raising an
1045 exception when there is trailing garbage after the first JSON
1046 object, it will silently stop parsing there and return the number
1047 of characters consumed so far.
1048
1049 This is useful if your JSON texts are not delimited by an outer
1050 protocol and you need to know where the JSON text ends.
1051
1052 Cpanel::JSON::XS->new->decode_prefix ("[1] the tail")
1053 => ([1], 3)
1054
1055 $json->to_json ($perl_hash_or_arrayref)
1056 Deprecated method for perl 5.8 and newer. Use encode_json instead.
1057
1058 $json->from_json ($utf8_encoded_json_text)
1059 Deprecated method for perl 5.8 and newer. Use decode_json instead.
1060
1062 In some cases, there is the need for incremental parsing of JSON texts.
1063 While this module always has to keep both JSON text and resulting Perl
1064 data structure in memory at one time, it does allow you to parse a JSON
1065 stream incrementally. It does so by accumulating text until it has a
1066 full JSON object, which it then can decode. This process is similar to
1067 using "decode_prefix" to see if a full JSON object is available, but is
1068 much more efficient (and can be implemented with a minimum of method
1069 calls).
1070
1071 Cpanel::JSON::XS will only attempt to parse the JSON text once it is
1072 sure it has enough text to get a decisive result, using a very simple
1073 but truly incremental parser. This means that it sometimes won't stop
1074 as early as the full parser, for example, it doesn't detect mismatched
1075 parentheses. The only thing it guarantees is that it starts decoding as
1076 soon as a syntactically valid JSON text has been seen. This means you
1077 need to set resource limits (e.g. "max_size") to ensure the parser will
1078 stop parsing in the presence if syntax errors.
1079
1080 The following methods implement this incremental parser.
1081
1082 [void, scalar or list context] = $json->incr_parse ([$string])
1083 This is the central parsing function. It can both append new text
1084 and extract objects from the stream accumulated so far (both of
1085 these functions are optional).
1086
1087 If $string is given, then this string is appended to the already
1088 existing JSON fragment stored in the $json object.
1089
1090 After that, if the function is called in void context, it will
1091 simply return without doing anything further. This can be used to
1092 add more text in as many chunks as you want.
1093
1094 If the method is called in scalar context, then it will try to
1095 extract exactly one JSON object. If that is successful, it will
1096 return this object, otherwise it will return "undef". If there is a
1097 parse error, this method will croak just as "decode" would do (one
1098 can then use "incr_skip" to skip the erroneous part). This is the
1099 most common way of using the method.
1100
1101 And finally, in list context, it will try to extract as many
1102 objects from the stream as it can find and return them, or the
1103 empty list otherwise. For this to work, there must be no separators
1104 between the JSON objects or arrays, instead they must be
1105 concatenated back-to-back. If an error occurs, an exception will be
1106 raised as in the scalar context case. Note that in this case, any
1107 previously-parsed JSON texts will be lost.
1108
1109 Example: Parse some JSON arrays/objects in a given string and
1110 return them.
1111
1112 my @objs = Cpanel::JSON::XS->new->incr_parse ("[5][7][1,2]");
1113
1114 $lvalue_string = $json->incr_text (>5.8 only)
1115 This method returns the currently stored JSON fragment as an
1116 lvalue, that is, you can manipulate it. This only works when a
1117 preceding call to "incr_parse" in scalar context successfully
1118 returned an object, and 2. only with Perl >= 5.8
1119
1120 Under all other circumstances you must not call this function (I
1121 mean it. although in simple tests it might actually work, it will
1122 fail under real world conditions). As a special exception, you can
1123 also call this method before having parsed anything.
1124
1125 This function is useful in two cases: a) finding the trailing text
1126 after a JSON object or b) parsing multiple JSON objects separated
1127 by non-JSON text (such as commas).
1128
1129 $json->incr_skip
1130 This will reset the state of the incremental parser and will remove
1131 the parsed text from the input buffer so far. This is useful after
1132 "incr_parse" died, in which case the input buffer and incremental
1133 parser state is left unchanged, to skip the text parsed so far and
1134 to reset the parse state.
1135
1136 The difference to "incr_reset" is that only text until the parse
1137 error occurred is removed.
1138
1139 $json->incr_reset
1140 This completely resets the incremental parser, that is, after this
1141 call, it will be as if the parser had never parsed anything.
1142
1143 This is useful if you want to repeatedly parse JSON objects and
1144 want to ignore any trailing data, which means you have to reset the
1145 parser after each successful decode.
1146
1147 LIMITATIONS
1148 All options that affect decoding are supported, except "allow_nonref".
1149 The reason for this is that it cannot be made to work sensibly: JSON
1150 objects and arrays are self-delimited, i.e. you can concatenate them
1151 back to back and still decode them perfectly. This does not hold true
1152 for JSON numbers, however.
1153
1154 For example, is the string 1 a single JSON number, or is it simply the
1155 start of 12? Or is 12 a single JSON number, or the concatenation of 1
1156 and 2? In neither case you can tell, and this is why Cpanel::JSON::XS
1157 takes the conservative route and disallows this case.
1158
1159 EXAMPLES
1160 Some examples will make all this clearer. First, a simple example that
1161 works similarly to "decode_prefix": We want to decode the JSON object
1162 at the start of a string and identify the portion after the JSON
1163 object:
1164
1165 my $text = "[1,2,3] hello";
1166
1167 my $json = new Cpanel::JSON::XS;
1168
1169 my $obj = $json->incr_parse ($text)
1170 or die "expected JSON object or array at beginning of string";
1171
1172 my $tail = $json->incr_text;
1173 # $tail now contains " hello"
1174
1175 Easy, isn't it?
1176
1177 Now for a more complicated example: Imagine a hypothetical protocol
1178 where you read some requests from a TCP stream, and each request is a
1179 JSON array, without any separation between them (in fact, it is often
1180 useful to use newlines as "separators", as these get interpreted as
1181 whitespace at the start of the JSON text, which makes it possible to
1182 test said protocol with "telnet"...).
1183
1184 Here is how you'd do it (it is trivial to write this in an event-based
1185 manner):
1186
1187 my $json = new Cpanel::JSON::XS;
1188
1189 # read some data from the socket
1190 while (sysread $socket, my $buf, 4096) {
1191
1192 # split and decode as many requests as possible
1193 for my $request ($json->incr_parse ($buf)) {
1194 # act on the $request
1195 }
1196 }
1197
1198 Another complicated example: Assume you have a string with JSON objects
1199 or arrays, all separated by (optional) comma characters (e.g. "[1],[2],
1200 [3]"). To parse them, we have to skip the commas between the JSON
1201 texts, and here is where the lvalue-ness of "incr_text" comes in
1202 useful:
1203
1204 my $text = "[1],[2], [3]";
1205 my $json = new Cpanel::JSON::XS;
1206
1207 # void context, so no parsing done
1208 $json->incr_parse ($text);
1209
1210 # now extract as many objects as possible. note the
1211 # use of scalar context so incr_text can be called.
1212 while (my $obj = $json->incr_parse) {
1213 # do something with $obj
1214
1215 # now skip the optional comma
1216 $json->incr_text =~ s/^ \s* , //x;
1217 }
1218
1219 Now lets go for a very complex example: Assume that you have a gigantic
1220 JSON array-of-objects, many gigabytes in size, and you want to parse
1221 it, but you cannot load it into memory fully (this has actually
1222 happened in the real world :).
1223
1224 Well, you lost, you have to implement your own JSON parser. But
1225 Cpanel::JSON::XS can still help you: You implement a (very simple)
1226 array parser and let JSON decode the array elements, which are all full
1227 JSON objects on their own (this wouldn't work if the array elements
1228 could be JSON numbers, for example):
1229
1230 my $json = new Cpanel::JSON::XS;
1231
1232 # open the monster
1233 open my $fh, "<bigfile.json"
1234 or die "bigfile: $!";
1235
1236 # first parse the initial "["
1237 for (;;) {
1238 sysread $fh, my $buf, 65536
1239 or die "read error: $!";
1240 $json->incr_parse ($buf); # void context, so no parsing
1241
1242 # Exit the loop once we found and removed(!) the initial "[".
1243 # In essence, we are (ab-)using the $json object as a simple scalar
1244 # we append data to.
1245 last if $json->incr_text =~ s/^ \s* \[ //x;
1246 }
1247
1248 # now we have the skipped the initial "[", so continue
1249 # parsing all the elements.
1250 for (;;) {
1251 # in this loop we read data until we got a single JSON object
1252 for (;;) {
1253 if (my $obj = $json->incr_parse) {
1254 # do something with $obj
1255 last;
1256 }
1257
1258 # add more data
1259 sysread $fh, my $buf, 65536
1260 or die "read error: $!";
1261 $json->incr_parse ($buf); # void context, so no parsing
1262 }
1263
1264 # in this loop we read data until we either found and parsed the
1265 # separating "," between elements, or the final "]"
1266 for (;;) {
1267 # first skip whitespace
1268 $json->incr_text =~ s/^\s*//;
1269
1270 # if we find "]", we are done
1271 if ($json->incr_text =~ s/^\]//) {
1272 print "finished.\n";
1273 exit;
1274 }
1275
1276 # if we find ",", we can continue with the next element
1277 if ($json->incr_text =~ s/^,//) {
1278 last;
1279 }
1280
1281 # if we find anything else, we have a parse error!
1282 if (length $json->incr_text) {
1283 die "parse error near ", $json->incr_text;
1284 }
1285
1286 # else add more data
1287 sysread $fh, my $buf, 65536
1288 or die "read error: $!";
1289 $json->incr_parse ($buf); # void context, so no parsing
1290 }
1291
1292 This is a complex example, but most of the complexity comes from the
1293 fact that we are trying to be correct (bear with me if I am wrong, I
1294 never ran the above example :).
1295
1297 Detect all unicode Byte Order Marks on decode. Which are UTF-8,
1298 UTF-16LE, UTF-16BE, UTF-32LE and UTF-32BE.
1299
1300 The BOM encoding is set only for one specific decode call, it does not
1301 change the state of the JSON object.
1302
1303 Warning: With perls older than 5.20 you need load the Encode module
1304 before loading a multibyte BOM, i.e. >= UTF-16. Otherwise an error is
1305 thrown. This is an implementation limitation and might get fixed later.
1306
1307 See <https://tools.ietf.org/html/rfc7159#section-8.1> "JSON text SHALL
1308 be encoded in UTF-8, UTF-16, or UTF-32."
1309
1310 "Implementations MUST NOT add a byte order mark to the beginning of a
1311 JSON text", "implementations (...) MAY ignore the presence of a byte
1312 order mark rather than treating it as an error".
1313
1314 See also <http://www.unicode.org/faq/utf_bom.html#BOM>.
1315
1316 Beware that Cpanel::JSON::XS is currently the only JSON module which
1317 does accept and decode a BOM.
1318
1319 The latest JSON spec
1320 <https://www.greenbytes.de/tech/webdav/rfc8259.html#character.encoding>
1321 forbid the usage of UTF-16 or UTF-32, the character encoding is UTF-8.
1322 Thus in subsequent updates BOM's of UTF-16 or UTF-32 will throw an
1323 error.
1324
1326 This section describes how Cpanel::JSON::XS maps Perl values to JSON
1327 values and vice versa. These mappings are designed to "do the right
1328 thing" in most circumstances automatically, preserving round-tripping
1329 characteristics (what you put in comes out as something equivalent).
1330
1331 For the more enlightened: note that in the following descriptions,
1332 lowercase perl refers to the Perl interpreter, while uppercase Perl
1333 refers to the abstract Perl language itself.
1334
1335 JSON -> PERL
1336 object
1337 A JSON object becomes a reference to a hash in Perl. No ordering of
1338 object keys is preserved (JSON does not preserve object key
1339 ordering itself).
1340
1341 array
1342 A JSON array becomes a reference to an array in Perl.
1343
1344 string
1345 A JSON string becomes a string scalar in Perl - Unicode codepoints
1346 in JSON are represented by the same codepoints in the Perl string,
1347 so no manual decoding is necessary.
1348
1349 number
1350 A JSON number becomes either an integer, numeric (floating point)
1351 or string scalar in perl, depending on its range and any fractional
1352 parts. On the Perl level, there is no difference between those as
1353 Perl handles all the conversion details, but an integer may take
1354 slightly less memory and might represent more values exactly than
1355 floating point numbers.
1356
1357 If the number consists of digits only, Cpanel::JSON::XS will try to
1358 represent it as an integer value. If that fails, it will try to
1359 represent it as a numeric (floating point) value if that is
1360 possible without loss of precision. Otherwise it will preserve the
1361 number as a string value (in which case you lose roundtripping
1362 ability, as the JSON number will be re-encoded to a JSON string).
1363
1364 Numbers containing a fractional or exponential part will always be
1365 represented as numeric (floating point) values, possibly at a loss
1366 of precision (in which case you might lose perfect roundtripping
1367 ability, but the JSON number will still be re-encoded as a JSON
1368 number).
1369
1370 Note that precision is not accuracy - binary floating point values
1371 cannot represent most decimal fractions exactly, and when
1372 converting from and to floating point, "Cpanel::JSON::XS" only
1373 guarantees precision up to but not including the least significant
1374 bit.
1375
1376 true, false
1377 When "unblessed_bool" is set to true, then JSON "true" becomes 1
1378 and JSON "false" becomes 0.
1379
1380 Otherwise these JSON atoms become "JSON::PP::true" and
1381 "JSON::PP::false", respectively. They are "JSON::PP::Boolean"
1382 objects and are overloaded to act almost exactly like the numbers 1
1383 and 0. You can check whether a scalar is a JSON boolean by using
1384 the "Cpanel::JSON::XS::is_bool" function.
1385
1386 The other round, from perl to JSON, "!0" which is represented as
1387 "yes" becomes "true", and "!1" which is represented as "no" becomes
1388 "false".
1389
1390 Via Cpanel::JSON::XS::Type you can now even force negation in
1391 "encode", without overloading of "!":
1392
1393 my $false = Cpanel::JSON::XS::false;
1394 print($json->encode([!$false], [JSON_TYPE_BOOL]));
1395 => [true]
1396
1397 null
1398 A JSON null atom becomes "undef" in Perl.
1399
1400 shell-style comments ("# text")
1401 As a nonstandard extension to the JSON syntax that is enabled by
1402 the "relaxed" setting, shell-style comments are allowed. They can
1403 start anywhere outside strings and go till the end of the line.
1404
1405 tagged values ("(tag)value").
1406 Another nonstandard extension to the JSON syntax, enabled with the
1407 "allow_tags" setting, are tagged values. In this implementation,
1408 the tag must be a perl package/class name encoded as a JSON string,
1409 and the value must be a JSON array encoding optional constructor
1410 arguments.
1411
1412 See "OBJECT SERIALIZATION", below, for details.
1413
1414 PERL -> JSON
1415 The mapping from Perl to JSON is slightly more difficult, as Perl is a
1416 truly typeless language, so we can only guess which JSON type is meant
1417 by a Perl value.
1418
1419 hash references
1420 Perl hash references become JSON objects. As there is no inherent
1421 ordering in hash keys (or JSON objects), they will usually be
1422 encoded in a pseudo-random order that can change between runs of
1423 the same program but stays generally the same within a single run
1424 of a program. Cpanel::JSON::XS can optionally sort the hash keys
1425 (determined by the canonical flag), so the same datastructure will
1426 serialize to the same JSON text (given same settings and version of
1427 Cpanel::JSON::XS), but this incurs a runtime overhead and is only
1428 rarely useful, e.g. when you want to compare some JSON text against
1429 another for equality.
1430
1431 array references
1432 Perl array references become JSON arrays.
1433
1434 other references
1435 Other unblessed references are generally not allowed and will cause
1436 an exception to be thrown, except for references to the integers 0
1437 and 1, which get turned into "false" and "true" atoms in JSON.
1438
1439 With the option "allow_stringify", you can ignore the exception and
1440 return the stringification of the perl value.
1441
1442 With the option "allow_unknown", you can ignore the exception and
1443 return "null" instead.
1444
1445 encode_json [\"x"] # => cannot encode reference to scalar 'SCALAR(0x..)'
1446 # unless the scalar is 0 or 1
1447 encode_json [\0, \1] # yields [false,true]
1448
1449 allow_stringify->encode_json [\"x"] # yields "x" unlike JSON::PP
1450 allow_unknown->encode_json [\"x"] # yields null as in JSON::PP
1451
1452 Cpanel::JSON::XS::true, Cpanel::JSON::XS::false
1453 These special values become JSON true and JSON false values,
1454 respectively. You can also use "\1" and "\0" or "!0" and "!1"
1455 directly if you want.
1456
1457 encode_json [Cpanel::JSON::XS::false, Cpanel::JSON::XS::true] # yields [false,true]
1458 encode_json [!1, !0], [JSON_TYPE_BOOL, JSON_TYPE_BOOL] # yields [false,true]
1459
1460 eq/ne comparisons with true, false:
1461
1462 false is eq to the empty string or the string 'false' or the
1463 special empty string "!!0" or "!1", i.e. "SV_NO", or the numbers 0
1464 or 0.0.
1465
1466 true is eq to the string 'true' or to the special string "!0" (i.e.
1467 "SV_YES") or to the numbers 1 or 1.0.
1468
1469 blessed objects
1470 Blessed objects are not directly representable in JSON, but
1471 "Cpanel::JSON::XS" allows various optional ways of handling
1472 objects. See "OBJECT SERIALIZATION", below, for details.
1473
1474 See the "allow_blessed" and "convert_blessed" methods on various
1475 options on how to deal with this: basically, you can choose between
1476 throwing an exception, encoding the reference as if it weren't
1477 blessed, use the objects overloaded stringification method or
1478 provide your own serializer method.
1479
1480 simple scalars
1481 Simple Perl scalars (any scalar that is not a reference) are the
1482 most difficult objects to encode: Cpanel::JSON::XS will encode
1483 undefined scalars or inf/nan as JSON "null" values and other
1484 scalars to either number or string in non-deterministic way which
1485 may be affected or changed by Perl version or any other loaded Perl
1486 module.
1487
1488 If you want to have stable and deterministic types in JSON encoder
1489 then use Cpanel::JSON::XS::Type.
1490
1491 Alternative way for deterministic types is to use "type_all_string"
1492 method when all perl scalars are encoded to JSON strings.
1493
1494 Non-deterministic behavior is following: scalars that have last
1495 been used in a string context before encoding as JSON strings, and
1496 anything else as number value:
1497
1498 # dump as number
1499 encode_json [2] # yields [2]
1500 encode_json [-3.0e17] # yields [-3e+17]
1501 my $value = 5; encode_json [$value] # yields [5]
1502
1503 # used as string, but the two representations are for the same number
1504 print $value;
1505 encode_json [$value] # yields [5]
1506
1507 # used as different string (non-matching dual-var)
1508 my $str = '0 but true';
1509 my $num = 1 + $str;
1510 encode_json [$num, $str] # yields [1,"0 but true"]
1511
1512 # undef becomes null
1513 encode_json [undef] # yields [null]
1514
1515 # inf or nan becomes null, unless you answered
1516 # "Do you want to handle inf/nan as strings" with yes
1517 encode_json [9**9**9] # yields [null]
1518
1519 You can force the type to be a JSON string by stringifying it:
1520
1521 my $x = 3.1; # some variable containing a number
1522 "$x"; # stringified
1523 $x .= ""; # another, more awkward way to stringify
1524 print $x; # perl does it for you, too, quite often
1525
1526 You can force the type to be a JSON number by numifying it:
1527
1528 my $x = "3"; # some variable containing a string
1529 $x += 0; # numify it, ensuring it will be dumped as a number
1530 $x *= 1; # same thing, the choice is yours.
1531
1532 Note that numerical precision has the same meaning as under Perl
1533 (so binary to decimal conversion follows the same rules as in Perl,
1534 which can differ to other languages). Also, your perl interpreter
1535 might expose extensions to the floating point numbers of your
1536 platform, such as infinities or NaN's - these cannot be represented
1537 in JSON, and thus null is returned instead. Optionally you can
1538 configure it to stringify inf and nan values.
1539
1540 OBJECT SERIALIZATION
1541 As JSON cannot directly represent Perl objects, you have to choose
1542 between a pure JSON representation (without the ability to deserialize
1543 the object automatically again), and a nonstandard extension to the
1544 JSON syntax, tagged values.
1545
1546 SERIALIZATION
1547
1548 What happens when "Cpanel::JSON::XS" encounters a Perl object depends
1549 on the "allow_blessed", "convert_blessed" and "allow_tags" settings,
1550 which are used in this order:
1551
1552 1. "allow_tags" is enabled and the object has a "FREEZE" method.
1553 In this case, "Cpanel::JSON::XS" uses the Types::Serialiser object
1554 serialization protocol to create a tagged JSON value, using a
1555 nonstandard extension to the JSON syntax.
1556
1557 This works by invoking the "FREEZE" method on the object, with the
1558 first argument being the object to serialize, and the second
1559 argument being the constant string "JSON" to distinguish it from
1560 other serializers.
1561
1562 The "FREEZE" method can return any number of values (i.e. zero or
1563 more). These values and the paclkage/classname of the object will
1564 then be encoded as a tagged JSON value in the following format:
1565
1566 ("classname")[FREEZE return values...]
1567
1568 e.g.:
1569
1570 ("URI")["http://www.google.com/"]
1571 ("MyDate")[2013,10,29]
1572 ("ImageData::JPEG")["Z3...VlCg=="]
1573
1574 For example, the hypothetical "My::Object" "FREEZE" method might
1575 use the objects "type" and "id" members to encode the object:
1576
1577 sub My::Object::FREEZE {
1578 my ($self, $serializer) = @_;
1579
1580 ($self->{type}, $self->{id})
1581 }
1582
1583 2. "convert_blessed" is enabled and the object has a "TO_JSON" method.
1584 In this case, the "TO_JSON" method of the object is invoked in
1585 scalar context. It must return a single scalar that can be directly
1586 encoded into JSON. This scalar replaces the object in the JSON
1587 text.
1588
1589 For example, the following "TO_JSON" method will convert all URI
1590 objects to JSON strings when serialized. The fact that these values
1591 originally were URI objects is lost.
1592
1593 sub URI::TO_JSON {
1594 my ($uri) = @_;
1595 $uri->as_string
1596 }
1597
1598 3. "convert_blessed" is enabled and the object has a stringification
1599 overload.
1600 In this case, the overloaded "" method of the object is invoked in
1601 scalar context. It must return a single scalar that can be directly
1602 encoded into JSON. This scalar replaces the object in the JSON
1603 text.
1604
1605 For example, the following "" method will convert all URI objects
1606 to JSON strings when serialized. The fact that these values
1607 originally were URI objects is lost.
1608
1609 package URI;
1610 use overload '""' => sub { shift->as_string };
1611
1612 4. "allow_blessed" is enabled.
1613 The object will be serialized as a JSON null value.
1614
1615 5. none of the above
1616 If none of the settings are enabled or the respective methods are
1617 missing, "Cpanel::JSON::XS" throws an exception.
1618
1619 DESERIALIZATION
1620
1621 For deserialization there are only two cases to consider: either
1622 nonstandard tagging was used, in which case "allow_tags" decides, or
1623 objects cannot be automatically be deserialized, in which case you can
1624 use postprocessing or the "filter_json_object" or
1625 "filter_json_single_key_object" callbacks to get some real objects our
1626 of your JSON.
1627
1628 This section only considers the tagged value case: I a tagged JSON
1629 object is encountered during decoding and "allow_tags" is disabled, a
1630 parse error will result (as if tagged values were not part of the
1631 grammar).
1632
1633 If "allow_tags" is enabled, "Cpanel::JSON::XS" will look up the "THAW"
1634 method of the package/classname used during serialization (it will not
1635 attempt to load the package as a Perl module). If there is no such
1636 method, the decoding will fail with an error.
1637
1638 Otherwise, the "THAW" method is invoked with the classname as first
1639 argument, the constant string "JSON" as second argument, and all the
1640 values from the JSON array (the values originally returned by the
1641 "FREEZE" method) as remaining arguments.
1642
1643 The method must then return the object. While technically you can
1644 return any Perl scalar, you might have to enable the "enable_nonref"
1645 setting to make that work in all cases, so better return an actual
1646 blessed reference.
1647
1648 As an example, let's implement a "THAW" function that regenerates the
1649 "My::Object" from the "FREEZE" example earlier:
1650
1651 sub My::Object::THAW {
1652 my ($class, $serializer, $type, $id) = @_;
1653
1654 $class->new (type => $type, id => $id)
1655 }
1656
1657 See the "SECURITY CONSIDERATIONS" section below. Allowing external json
1658 objects being deserialized to perl objects is usually a very bad idea.
1659
1661 The interested reader might have seen a number of flags that signify
1662 encodings or codesets - "utf8", "latin1", "binary" and "ascii". There
1663 seems to be some confusion on what these do, so here is a short
1664 comparison:
1665
1666 "utf8" controls whether the JSON text created by "encode" (and expected
1667 by "decode") is UTF-8 encoded or not, while "latin1" and "ascii" only
1668 control whether "encode" escapes character values outside their
1669 respective codeset range. Neither of these flags conflict with each
1670 other, although some combinations make less sense than others.
1671
1672 Care has been taken to make all flags symmetrical with respect to
1673 "encode" and "decode", that is, texts encoded with any combination of
1674 these flag values will be correctly decoded when the same flags are
1675 used - in general, if you use different flag settings while encoding
1676 vs. when decoding you likely have a bug somewhere.
1677
1678 Below comes a verbose discussion of these flags. Note that a "codeset"
1679 is simply an abstract set of character-codepoint pairs, while an
1680 encoding takes those codepoint numbers and encodes them, in our case
1681 into octets. Unicode is (among other things) a codeset, UTF-8 is an
1682 encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets and
1683 encodings at the same time, which can be confusing.
1684
1685 "utf8" flag disabled
1686 When "utf8" is disabled (the default), then "encode"/"decode"
1687 generate and expect Unicode strings, that is, characters with high
1688 ordinal Unicode values (> 255) will be encoded as such characters,
1689 and likewise such characters are decoded as-is, no changes to them
1690 will be done, except "(re-)interpreting" them as Unicode codepoints
1691 or Unicode characters, respectively (to Perl, these are the same
1692 thing in strings unless you do funny/weird/dumb stuff).
1693
1694 This is useful when you want to do the encoding yourself (e.g. when
1695 you want to have UTF-16 encoded JSON texts) or when some other
1696 layer does the encoding for you (for example, when printing to a
1697 terminal using a filehandle that transparently encodes to UTF-8 you
1698 certainly do NOT want to UTF-8 encode your data first and have Perl
1699 encode it another time).
1700
1701 "utf8" flag enabled
1702 If the "utf8"-flag is enabled, "encode"/"decode" will encode all
1703 characters using the corresponding UTF-8 multi-byte sequence, and
1704 will expect your input strings to be encoded as UTF-8, that is, no
1705 "character" of the input string must have any value > 255, as UTF-8
1706 does not allow that.
1707
1708 The "utf8" flag therefore switches between two modes: disabled
1709 means you will get a Unicode string in Perl, enabled means you get
1710 an UTF-8 encoded octet/binary string in Perl.
1711
1712 "latin1", "binary" or "ascii" flags enabled
1713 With "latin1" (or "ascii") enabled, "encode" will escape characters
1714 with ordinal values > 255 (> 127 with "ascii") and encode the
1715 remaining characters as specified by the "utf8" flag. With
1716 "binary" enabled, ordinal values > 255 are illegal.
1717
1718 If "utf8" is disabled, then the result is also correctly encoded in
1719 those character sets (as both are proper subsets of Unicode,
1720 meaning that a Unicode string with all character values < 256 is
1721 the same thing as a ISO-8859-1 string, and a Unicode string with
1722 all character values < 128 is the same thing as an ASCII string in
1723 Perl).
1724
1725 If "utf8" is enabled, you still get a correct UTF-8-encoded string,
1726 regardless of these flags, just some more characters will be
1727 escaped using "\uXXXX" then before.
1728
1729 Note that ISO-8859-1-encoded strings are not compatible with UTF-8
1730 encoding, while ASCII-encoded strings are. That is because the
1731 ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the
1732 ISO-8859-1 codeset being a subset of Unicode), while ASCII is.
1733
1734 Surprisingly, "decode" will ignore these flags and so treat all
1735 input values as governed by the "utf8" flag. If it is disabled,
1736 this allows you to decode ISO-8859-1- and ASCII-encoded strings, as
1737 both strict subsets of Unicode. If it is enabled, you can correctly
1738 decode UTF-8 encoded strings.
1739
1740 So neither "latin1", "binary" nor "ascii" are incompatible with the
1741 "utf8" flag - they only govern when the JSON output engine escapes
1742 a character or not.
1743
1744 The main use for "latin1" or "binary" is to relatively efficiently
1745 store binary data as JSON, at the expense of breaking compatibility
1746 with most JSON decoders.
1747
1748 The main use for "ascii" is to force the output to not contain
1749 characters with values > 127, which means you can interpret the
1750 resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about
1751 any character set and 8-bit-encoding, and still get the same data
1752 structure back. This is useful when your channel for JSON transfer
1753 is not 8-bit clean or the encoding might be mangled in between
1754 (e.g. in mail), and works because ASCII is a proper subset of most
1755 8-bit and multibyte encodings in use in the world.
1756
1757 JSON and ECMAscript
1758 JSON syntax is based on how literals are represented in javascript (the
1759 not-standardized predecessor of ECMAscript) which is presumably why it
1760 is called "JavaScript Object Notation".
1761
1762 However, JSON is not a subset (and also not a superset of course) of
1763 ECMAscript (the standard) or javascript (whatever browsers actually
1764 implement).
1765
1766 If you want to use javascript's "eval" function to "parse" JSON, you
1767 might run into parse errors for valid JSON texts, or the resulting data
1768 structure might not be queryable:
1769
1770 One of the problems is that U+2028 and U+2029 are valid characters
1771 inside JSON strings, but are not allowed in ECMAscript string literals,
1772 so the following Perl fragment will not output something that can be
1773 guaranteed to be parsable by javascript's "eval":
1774
1775 use Cpanel::JSON::XS;
1776
1777 print encode_json [chr 0x2028];
1778
1779 The right fix for this is to use a proper JSON parser in your
1780 javascript programs, and not rely on "eval" (see for example Douglas
1781 Crockford's json2.js parser).
1782
1783 If this is not an option, you can, as a stop-gap measure, simply encode
1784 to ASCII-only JSON:
1785
1786 use Cpanel::JSON::XS;
1787
1788 print Cpanel::JSON::XS->new->ascii->encode ([chr 0x2028]);
1789
1790 Note that this will enlarge the resulting JSON text quite a bit if you
1791 have many non-ASCII characters. You might be tempted to run some
1792 regexes to only escape U+2028 and U+2029, e.g.:
1793
1794 # DO NOT USE THIS!
1795 my $json = Cpanel::JSON::XS->new->utf8->encode ([chr 0x2028]);
1796 $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028
1797 $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029
1798 print $json;
1799
1800 Note that this is a bad idea: the above only works for U+2028 and
1801 U+2029 and thus only for fully ECMAscript-compliant parsers. Many
1802 existing javascript implementations, however, have issues with other
1803 characters as well - using "eval" naively simply will cause problems.
1804
1805 Another problem is that some javascript implementations reserve some
1806 property names for their own purposes (which probably makes them non-
1807 ECMAscript-compliant). For example, Iceweasel reserves the "__proto__"
1808 property name for its own purposes.
1809
1810 If that is a problem, you could parse try to filter the resulting JSON
1811 output for these property strings, e.g.:
1812
1813 $json =~ s/"__proto__"\s*:/"__proto__renamed":/g;
1814
1815 This works because "__proto__" is not valid outside of strings, so
1816 every occurrence of ""__proto__"\s*:" must be a string used as property
1817 name.
1818
1819 Unicode non-characters between U+FFFD and U+10FFFF are decoded either
1820 to the recommended U+FFFD REPLACEMENT CHARACTER (see Unicode PR #121:
1821 Recommended Practice for Replacement Characters), or in the binary or
1822 relaxed mode left as is, keeping the illegal non-characters as before.
1823
1824 Raw non-Unicode characters outside the valid unicode range fail now to
1825 parse, because "A string is a sequence of zero or more Unicode
1826 characters" RFC 7159 section 1 and "JSON text SHALL be encoded in
1827 Unicode RFC 7159 section 8.1. We use now the UTF8_DISALLOW_SUPER flag
1828 when parsing unicode.
1829
1830 If you know of other incompatibilities, please let me know.
1831
1832 JSON and YAML
1833 You often hear that JSON is a subset of YAML. in general, there is no
1834 way to configure JSON::XS to output a data structure as valid YAML that
1835 works in all cases. If you really must use Cpanel::JSON::XS to
1836 generate YAML, you should use this algorithm (subject to change in
1837 future versions):
1838
1839 my $to_yaml = Cpanel::JSON::XS->new->utf8->space_after (1);
1840 my $yaml = $to_yaml->encode ($ref) . "\n";
1841
1842 This will usually generate JSON texts that also parse as valid YAML.
1843
1844 SPEED
1845 It seems that JSON::XS is surprisingly fast, as shown in the following
1846 tables. They have been generated with the help of the "eg/bench"
1847 program in the JSON::XS distribution, to make it easy to compare on
1848 your own system.
1849
1850 JSON::XS is with Data::MessagePack and Sereal one of the fastest
1851 serializers, because JSON and JSON::XS do not support backrefs (no
1852 graph structures), only trees. Storable supports backrefs, i.e. graphs.
1853 Data::MessagePack encodes its data binary (as Storable) and supports
1854 only very simple subset of JSON.
1855
1856 First comes a comparison between various modules using a very short
1857 single-line JSON string (also available at
1858 <http://dist.schmorp.de/misc/json/short.json>).
1859
1860 {"method": "handleMessage", "params": ["user1",
1861 "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7,
1862 1, 0]}
1863
1864 It shows the number of encodes/decodes per second (JSON::XS uses the
1865 functional interface, while Cpanel::JSON::XS/2 uses the OO interface
1866 with pretty-printing and hash key sorting enabled, Cpanel::JSON::XS/3
1867 enables shrink. JSON::DWIW/DS uses the deserialize function, while
1868 JSON::DWIW::FJ uses the from_json method). Higher is better:
1869
1870 module | encode | decode |
1871 --------------|------------|------------|
1872 JSON::DWIW/DS | 86302.551 | 102300.098 |
1873 JSON::DWIW/FJ | 86302.551 | 75983.768 |
1874 JSON::PP | 15827.562 | 6638.658 |
1875 JSON::Syck | 63358.066 | 47662.545 |
1876 JSON::XS | 511500.488 | 511500.488 |
1877 JSON::XS/2 | 291271.111 | 388361.481 |
1878 JSON::XS/3 | 361577.931 | 361577.931 |
1879 Storable | 66788.280 | 265462.278 |
1880 --------------+------------+------------+
1881
1882 That is, JSON::XS is almost six times faster than JSON::DWIW on
1883 encoding, about five times faster on decoding, and over thirty to
1884 seventy times faster than JSON's pure perl implementation. It also
1885 compares favourably to Storable for small amounts of data.
1886
1887 Using a longer test string (roughly 18KB, generated from Yahoo! Locals
1888 search API (<http://dist.schmorp.de/misc/json/long.json>).
1889
1890 module | encode | decode |
1891 --------------|------------|------------|
1892 JSON::DWIW/DS | 1647.927 | 2673.916 |
1893 JSON::DWIW/FJ | 1630.249 | 2596.128 |
1894 JSON::PP | 400.640 | 62.311 |
1895 JSON::Syck | 1481.040 | 1524.869 |
1896 JSON::XS | 20661.596 | 9541.183 |
1897 JSON::XS/2 | 10683.403 | 9416.938 |
1898 JSON::XS/3 | 20661.596 | 9400.054 |
1899 Storable | 19765.806 | 10000.725 |
1900 --------------+------------+------------+
1901
1902 Again, JSON::XS leads by far (except for Storable which non-
1903 surprisingly decodes a bit faster).
1904
1905 On large strings containing lots of high Unicode characters, some
1906 modules (such as JSON::PC) seem to decode faster than JSON::XS, but the
1907 result will be broken due to missing (or wrong) Unicode handling.
1908 Others refuse to decode or encode properly, so it was impossible to
1909 prepare a fair comparison table for that case.
1910
1911 For updated graphs see
1912 <https://github.com/Sereal/Sereal/wiki/Sereal-Comparison-Graphs>
1913
1915 As long as you only serialize data that can be directly expressed in
1916 JSON, "Cpanel::JSON::XS" is incapable of generating invalid JSON output
1917 (modulo bugs, but "JSON::XS" has found more bugs in the official JSON
1918 testsuite (1) than the official JSON testsuite has found in "JSON::XS"
1919 (0)). "Cpanel::JSON::XS" is currently the only known JSON decoder
1920 which passes all <http://seriot.ch/parsing_json.html> tests, while
1921 being the fastest also.
1922
1923 When you have trouble decoding JSON generated by this module using
1924 other decoders, then it is very likely that you have an encoding
1925 mismatch or the other decoder is broken.
1926
1927 When decoding, "JSON::XS" is strict by default and will likely catch
1928 all errors. There are currently two settings that change this:
1929 "relaxed" makes "JSON::XS" accept (but not generate) some non-standard
1930 extensions, and "allow_tags" or "allow_blessed" will allow you to
1931 encode and decode Perl objects, at the cost of being totally insecure
1932 and not outputting valid JSON anymore.
1933
1934 JSON-XS-3.01 broke interoperability with JSON-2.90 with booleans. See
1935 JSON.
1936
1937 Cpanel::JSON::XS needs to know the JSON and JSON::XS versions to be
1938 able work with those objects, especially when encoding a booleans like
1939 "{"is_true":true}". So you need to load these modules before.
1940
1941 true/false overloading and boolean representations are supported.
1942
1943 JSON::XS and JSON::PP representations are accepted and older JSON::XS
1944 accepts Cpanel::JSON::XS booleans. All JSON modules JSON, JSON, PP,
1945 JSON::XS, Cpanel::JSON::XS produce JSON::PP::Boolean objects, just Mojo
1946 and JSON::YAJL not. Mojo produces Mojo::JSON::_Bool and
1947 JSON::YAJL::Parser just an unblessed IV.
1948
1949 Cpanel::JSON::XS accepts JSON::PP::Boolean and Mojo::JSON::_Bool
1950 objects as booleans.
1951
1952 I cannot think of any reason to still use JSON::XS anymore.
1953
1954 TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS
1955 When you use "allow_tags" to use the extended (and also nonstandard and
1956 invalid) JSON syntax for serialized objects, and you still want to
1957 decode the generated serialize objects, you can run a regex to replace
1958 the tagged syntax by standard JSON arrays (it only works for "normal"
1959 package names without comma, newlines or single colons). First, the
1960 readable Perl version:
1961
1962 # if your FREEZE methods return no values, you need this replace first:
1963 $json =~ s/\( \s* (" (?: [^\\":,]+|\\.|::)* ") \s* \) \s* \[\s*\]/[$1]/gx;
1964
1965 # this works for non-empty constructor arg lists:
1966 $json =~ s/\( \s* (" (?: [^\\":,]+|\\.|::)* ") \s* \) \s* \[/[$1,/gx;
1967
1968 And here is a less readable version that is easy to adapt to other
1969 languages:
1970
1971 $json =~ s/\(\s*("([^\\":,]+|\\.|::)*")\s*\)\s*\[/[$1,/g;
1972
1973 Here is an ECMAScript version (same regex):
1974
1975 json = json.replace (/\(\s*("([^\\":,]+|\\.|::)*")\s*\)\s*\[/g, "[$1,");
1976
1977 Since this syntax converts to standard JSON arrays, it might be hard to
1978 distinguish serialized objects from normal arrays. You can prepend a
1979 "magic number" as first array element to reduce chances of a collision:
1980
1981 $json =~ s/\(\s*("([^\\":,]+|\\.|::)*")\s*\)\s*\[/["XU1peReLzT4ggEllLanBYq4G9VzliwKF",$1,/g;
1982
1983 And after decoding the JSON text, you could walk the data structure
1984 looking for arrays with a first element of
1985 "XU1peReLzT4ggEllLanBYq4G9VzliwKF".
1986
1987 The same approach can be used to create the tagged format with another
1988 encoder. First, you create an array with the magic string as first
1989 member, the classname as second, and constructor arguments last, encode
1990 it as part of your JSON structure, and then:
1991
1992 $json =~ s/\[\s*"XU1peReLzT4ggEllLanBYq4G9VzliwKF"\s*,\s*("([^\\":,]+|\\.|::)*")\s*,/($1)[/g;
1993
1994 Again, this has some limitations - the magic string must not be encoded
1995 with character escapes, and the constructor arguments must be non-
1996 empty.
1997
1999 Since this module was written, Google has written a new JSON RFC, RFC
2000 7159 (and RFC7158). Unfortunately, this RFC breaks compatibility with
2001 both the original JSON specification on www.json.org and RFC4627.
2002
2003 As far as I can see, you can get partial compatibility when parsing by
2004 using "->allow_nonref". However, consider the security implications of
2005 doing so.
2006
2007 I haven't decided yet when to break compatibility with RFC4627 by
2008 default (and potentially leave applications insecure) and change the
2009 default to follow RFC7159, but application authors are well advised to
2010 call "->allow_nonref(0)" even if this is the current default, if they
2011 cannot handle non-reference values, in preparation for the day when the
2012 default will change.
2013
2015 JSON::XS and Cpanel::JSON::XS are not only fast. JSON is generally the
2016 most secure serializing format, because it is the only one besides
2017 Data::MessagePack, which does not deserialize objects per default. For
2018 all languages, not just perl. The binary variant BSON (MongoDB) does
2019 more but is unsafe.
2020
2021 It is trivial for any attacker to create such serialized objects in
2022 JSON and trick perl into expanding them, thereby triggering certain
2023 methods. Watch <https://www.youtube.com/watch?v=Gzx6KlqiIZE> for an
2024 exploit demo for "CVE-2015-1592 SixApart MovableType Storable Perl Code
2025 Execution" for a deserializer which expands objects. Deserializing
2026 even coderefs (methods, functions) or external data would be considered
2027 the most dangerous.
2028
2029 Security relevant overview of serializers regarding deserializing
2030 objects by default:
2031
2032 Objects Coderefs External Data
2033
2034 Data::Dumper YES YES YES
2035 Storable YES NO (def) NO
2036 Sereal YES NO NO
2037 YAML YES NO NO
2038 B::C YES YES YES
2039 B::Bytecode YES YES YES
2040 BSON YES YES NO
2041 JSON::SL YES NO YES
2042 JSON NO (def) NO NO
2043 Data::MessagePack NO NO NO
2044 XML NO NO YES
2045
2046 Pickle YES YES YES
2047 PHP Deserialize YES NO NO
2048
2049 When you are using JSON in a protocol, talking to untrusted potentially
2050 hostile creatures requires relatively few measures.
2051
2052 First of all, your JSON decoder should be secure, that is, should not
2053 have any buffer overflows. Obviously, this module should ensure that.
2054
2055 Second, you need to avoid resource-starving attacks. That means you
2056 should limit the size of JSON texts you accept, or make sure then when
2057 your resources run out, that's just fine (e.g. by using a separate
2058 process that can crash safely). The size of a JSON text in octets or
2059 characters is usually a good indication of the size of the resources
2060 required to decode it into a Perl structure. While JSON::XS can check
2061 the size of the JSON text, it might be too late when you already have
2062 it in memory, so you might want to check the size before you accept the
2063 string.
2064
2065 Third, Cpanel::JSON::XS recurses using the C stack when decoding
2066 objects and arrays. The C stack is a limited resource: for instance, on
2067 my amd64 machine with 8MB of stack size I can decode around 180k nested
2068 arrays but only 14k nested JSON objects (due to perl itself recursing
2069 deeply on croak to free the temporary). If that is exceeded, the
2070 program crashes. To be conservative, the default nesting limit is set
2071 to 512. If your process has a smaller stack, you should adjust this
2072 setting accordingly with the "max_depth" method.
2073
2074 Also keep in mind that Cpanel::JSON::XS might leak contents of your
2075 Perl data structures in its error messages, so when you serialize
2076 sensitive information you might want to make sure that exceptions
2077 thrown by JSON::XS will not end up in front of untrusted eyes.
2078
2079 If you are using Cpanel::JSON::XS to return packets to consumption by
2080 JavaScript scripts in a browser you should have a look at
2081 <http://blog.archive.jpsykes.com/47/practical-csrf-and-json-security/>
2082 to see whether you are vulnerable to some common attack vectors (which
2083 really are browser design bugs, but it is still you who will have to
2084 deal with it, as major browser developers care only for features, not
2085 about getting security right). You might also want to also look at
2086 Mojo::JSON special escape rules to prevent from XSS attacks.
2087
2089 TL;DR: Due to security concerns, Cpanel::JSON::XS will not allow scalar
2090 data in JSON texts by default - you need to create your own
2091 Cpanel::JSON::XS object and enable "allow_nonref":
2092
2093 my $json = JSON::XS->new->allow_nonref;
2094
2095 $text = $json->encode ($data);
2096 $data = $json->decode ($text);
2097
2098 The long version: JSON being an important and supposedly stable format,
2099 the IETF standardized it as RFC 4627 in 2006. Unfortunately the
2100 inventor of JSON Douglas Crockford unilaterally changed the definition
2101 of JSON in javascript. Rather than create a fork, the IETF decided to
2102 standardize the new syntax (apparently, so I as told, without finding
2103 it very amusing).
2104
2105 The biggest difference between the original JSON and the new JSON is
2106 that the new JSON supports scalars (anything other than arrays and
2107 objects) at the top-level of a JSON text. While this is strictly
2108 backwards compatible to older versions, it breaks a number of protocols
2109 that relied on sending JSON back-to-back, and is a minor security
2110 concern.
2111
2112 For example, imagine you have two banks communicating, and on one side,
2113 the JSON coder gets upgraded. Two messages, such as 10 and 1000 might
2114 then be confused to mean 101000, something that couldn't happen in the
2115 original JSON, because neither of these messages would be valid JSON.
2116
2117 If one side accepts these messages, then an upgrade in the coder on
2118 either side could result in this becoming exploitable.
2119
2120 This module has always allowed these messages as an optional extension,
2121 by default disabled. The security concerns are the reason why the
2122 default is still disabled, but future versions might/will likely
2123 upgrade to the newer RFC as default format, so you are advised to check
2124 your implementation and/or override the default with "->allow_nonref
2125 (0)" to ensure that future versions are safe.
2126
2128 Cpanel::JSON::XS has proper ithreads support, unlike JSON::XS. If you
2129 encounter any bugs with thread support please report them.
2130
2131 From Version 4.00 - 4.19 you couldn't encode true with threads::shared
2132 magic.
2133
2135 While the goal of the Cpanel::JSON::XS module is to be correct, that
2136 unfortunately does not mean it's bug-free, only that the author thinks
2137 its design is bug-free. If you keep reporting bugs and tests they will
2138 be fixed swiftly, though.
2139
2140 Since the JSON::XS author refuses to use a public bugtracker and
2141 prefers private emails, we use the tracker at github, so you might want
2142 to report any issues twice. Once in private to MLEHMANN to be fixed in
2143 JSON::XS and one to our the public tracker. Issues fixed by JSON::XS
2144 with a new release will also be backported to Cpanel::JSON::XS and
2145 5.6.2, as long as cPanel relies on 5.6.2 and Cpanel::JSON::XS as our
2146 serializer of choice.
2147
2148 <https://github.com/rurban/Cpanel-JSON-XS/issues>
2149
2151 This module is available under the same licences as perl, the Artistic
2152 license and the GPL.
2153
2155 The cpanel_json_xs command line utility for quick experiments.
2156
2157 JSON, JSON::XS, JSON::MaybeXS, Mojo::JSON, Mojo::JSON::MaybeXS,
2158 JSON::SL, JSON::DWIW, JSON::YAJL, JSON::Any, Test::JSON,
2159 Locale::Wolowitz, <https://metacpan.org/search?q=JSON>
2160
2161 <https://tools.ietf.org/html/rfc7159>
2162
2163 <https://tools.ietf.org/html/rfc4627>
2164
2166 Reini Urban <rurban@cpan.org>
2167
2168 Marc Lehmann <schmorp@schmorp.de>, http://home.schmorp.de/
2169
2171 Reini Urban <rurban@cpan.org>
2172
2173
2174
2175perl v5.36.0 2022-08-13 XS(3)