forked from rurban/Cpanel-JSON-XS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XS.pm
2438 lines (1732 loc) · 89.9 KB
/
XS.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Cpanel::JSON::XS;
our $VERSION = '4.36';
our $XS_VERSION = $VERSION;
# $VERSION = eval $VERSION;
=pod
=head1 NAME
Cpanel::JSON::XS - cPanel fork of JSON::XS, fast and correct serializing
=head1 SYNOPSIS
use Cpanel::JSON::XS;
# exported functions, they croak on error
# and expect/generate UTF-8
$utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
$perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
# OO-interface
$coder = Cpanel::JSON::XS->new->ascii->pretty->allow_nonref;
$pretty_printed_unencoded = $coder->encode ($perl_scalar);
$perl_scalar = $coder->decode ($unicode_json_text);
# Note that 5.6 misses most smart utf8 and encoding functionalities
# of newer releases.
# Note that L<JSON::MaybeXS> will automatically use Cpanel::JSON::XS
# if available, at virtually no speed overhead either, so you should
# be able to just:
use JSON::MaybeXS;
# and do the same things, except that you have a pure-perl fallback now.
Note that this module will be replaced by a new JSON::Safe module soon,
with the same API just guaranteed safe defaults.
=head1 DESCRIPTION
This module converts Perl data structures to JSON and vice versa. Its
primary goal is to be I<correct> and its secondary goal is to be
I<fast>. To reach the latter goal it was written in C.
As this is the n-th-something JSON module on CPAN, what was the reason
to write yet another JSON module? While it seems there are many JSON
modules, none of them correctly handle all corner cases, and in most cases
their maintainers are unresponsive, gone missing, or not listening to bug
reports for other reasons.
See below for the cPanel fork.
See MAPPING, below, on how Cpanel::JSON::XS maps perl values to JSON
values and vice versa.
=head2 FEATURES
=over 4
=item * correct Unicode handling
This module knows how to handle Unicode with Perl version higher than 5.8.5,
documents how and when it does so, and even documents what "correct" means.
=item * round-trip integrity
When you serialize a perl data structure using only data types supported
by JSON and Perl, the deserialized data structure is identical on the Perl
level. (e.g. the string "2.0" doesn't suddenly become "2" just because
it looks like a number). There I<are> minor exceptions to this, read the
MAPPING section below to learn about those.
=item * strict checking of JSON correctness
There is no guessing, no generating of illegal JSON texts by default,
and only JSON is accepted as input by default. the latter is a security
feature.
=item * fast
Compared to other JSON modules and other serializers such as Storable,
this module usually compares favourably in terms of speed, too.
=item * simple to use
This module has both a simple functional interface as well as an object
oriented interface.
=item * reasonably versatile output formats
You can choose between the most compact guaranteed-single-line format
possible (nice for simple line-based protocols), a pure-ASCII format
(for when your transport is not 8-bit clean, still supports the whole
Unicode range), or a pretty-printed format (for when you want to read that
stuff). Or you can combine those features in whatever way you like.
=back
=head2 cPanel fork
Since the original author MLEHMANN has no public
bugtracker, this cPanel fork sits now on github.
src repo: L<https://github.com/rurban/Cpanel-JSON-XS>
original: L<http://cvs.schmorp.de/JSON-XS/>
RT: L<https://github.com/rurban/Cpanel-JSON-XS/issues>
or L<https://rt.cpan.org/Public/Dist/Display.html?Queue=Cpanel-JSON-XS>
B<Changes to JSON::XS>
- bare hashkeys are now checked for utf8. (GH #209)
- stricter decode_json() as documented. non-refs are disallowed.
safe by default.
added a 2nd optional argument. decode() honors now allow_nonref.
- fixed encode of numbers for dual-vars. Different string
representations are preserved, but numbers with temporary strings
which represent the same number are here treated as numbers, not
strings. Cpanel::JSON::XS is a bit slower, but preserves numeric
types better.
- numbers ending with .0 stray numbers, are not converted to
integers. [#63] dual-vars which are represented as number not
integer (42+"bar" != 5.8.9) are now encoded as number (=> 42.0)
because internally it's now a NOK type. However !!1 which is
wrongly encoded in 5.8 as "1"/1.0 is still represented as integer.
- different handling of inf/nan. Default now to null, optionally with
stringify_infnan() to "inf"/"nan". [#28, #32]
- added C<binary> extension, non-JSON and non JSON parsable, allows
C<\xNN> and C<\NNN> sequences.
- 5.6.2 support; sacrificing some utf8 features (assuming bytes
all-over), no multi-byte unicode characters with 5.6.
- interop for true/false overloading. JSON::XS, JSON::PP and Mojo::JSON
representations for booleans are accepted and JSON::XS accepts
Cpanel::JSON::XS booleans [#13, #37]
Fixed overloading of booleans. Cpanel::JSON::XS::true stringifies again
to "1", not "true", analog to all other JSON modules.
- native boolean mapping of yes and no to true and false, as in YAML::XS.
In perl C<!0> is yes, C<!1> is no.
The JSON value true maps to 1, false maps to 0. [#39]
- support arbitrary stringification with encode, with convert_blessed
and allow_blessed.
- ithread support. Cpanel::JSON::XS is thread-safe, JSON::XS not
- is_bool can be called as method, JSON::XS::is_bool not.
- performance optimizations for threaded Perls
- relaxed mode, allowing many popular extensions
- protect our magic object from corruption by wrong or missing external
methods, like FREEZE/THAW or serialization with other methods.
- additional fixes for:
- #208 - no security-relevant out-of-bounds reading of module memory
when decoding hash keys without ending ':'
- [cpan #88061] AIX atof without USE_LONG_DOUBLE
- #10 unshare_hek crash
- #7, #29 avoid re-blessing where possible. It fails in JSON::XS for
READONLY values, i.e. restricted hashes.
- #41 overloading of booleans, use the object not the reference.
- #62 -Dusequadmath conversion and no SEGV.
- #72 parsing of values followed \0, like 1\0 does fail.
- #72 parsing of illegal unicode or non-unicode characters.
- #96 locale-insensitive numeric conversion.
- #154 numeric conversion fixed since 5.22, using the same strtold as perl5.
- #167 sort tied hashes with canonical.
- #212 fix utf8 object stringification
- public maintenance and bugtracker
- use ppport.h, sanify XS.xs comment styles, harness C coding style
- common::sense is optional. When available it is not used in the
published production module, just during development and testing.
- extended testsuite, passes all http://seriot.ch/projects/parsing_json.html
tests. In fact it is the only know JSON decoder which does so,
while also being the fastest.
- support many more options and methods from JSON::PP:
stringify_infnan, allow_unknown, allow_stringify, allow_barekey,
encode_stringify, allow_bignum, allow_singlequote, dupkeys_as_arrayref,
sort_by (partially), escape_slash, convert_blessed, ...
optional decode_json(, allow_nonref) arg.
relaxed implements allow_dupkeys.
- support all 5 unicode L<BOM|/BOM>'s: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE,
UTF-32BE, encoding internally to UTF-8.
=cut
our @ISA = qw(Exporter);
our @EXPORT = qw(encode_json decode_json to_json from_json);
sub to_json($@) {
if ($] >= 5.008) {
require Carp;
Carp::croak ("Cpanel::JSON::XS::to_json has been renamed to encode_json,".
" either downgrade to pre-2.0 versions of Cpanel::JSON::XS or".
" rename the call");
} else {
_to_json(@_);
}
}
sub from_json($@) {
if ($] >= 5.008) {
require Carp;
Carp::croak ("Cpanel::JSON::XS::from_json has been renamed to decode_json,".
" either downgrade to pre-2.0 versions of Cpanel::JSON::XS or".
" rename the call");
} else {
_from_json(@_);
}
}
use Exporter;
use XSLoader;
=head1 FUNCTIONAL INTERFACE
The following convenience methods are provided by this module. They are
exported by default:
=over 4
=item $json_text = encode_json $perl_scalar, [json_type]
Converts the given Perl data structure to a UTF-8 encoded, binary string
(that is, the string contains octets only). Croaks on error.
This function call is functionally identical to:
$json_text = Cpanel::JSON::XS->new->utf8->encode ($perl_scalar, $json_type)
Except being faster.
For the type argument see L<Cpanel::JSON::XS::Type>.
=item $perl_scalar = decode_json $json_text [, $allow_nonref [, my $json_type ] ]
The opposite of C<encode_json>: expects an UTF-8 (binary) string of an
json reference and tries to parse that as an UTF-8 encoded JSON text,
returning the resulting reference. Croaks on error.
This function call is functionally identical to:
$perl_scalar = Cpanel::JSON::XS->new->utf8->decode ($json_text, $json_type)
except being faster.
Note that older decode_json versions in Cpanel::JSON::XS older than
3.0116 and JSON::XS did not set allow_nonref but allowed them due to a
bug in the decoder.
If the new 2nd optional $allow_nonref argument is set and not false, the
C<allow_nonref> option will be set and the function will act is described
as in the relaxed RFC 7159 allowing all values such as objects,
arrays, strings, numbers, "null", "true", and "false".
See L</"OLD" VS. "NEW" JSON (RFC 4627 VS. RFC 7159)> below, why you don't
want to do that.
For the 3rd optional type argument see L<Cpanel::JSON::XS::Type>.
=item $is_boolean = Cpanel::JSON::XS::is_bool $scalar
Returns true if the passed scalar represents either C<JSON::PP::true>
or C<JSON::PP::false>, two constants that act like C<1> and C<0>,
respectively and are used to represent JSON C<true> and C<false>
values in Perl. (Also recognizes the booleans produced by L<JSON::XS>.)
See MAPPING, below, for more information on how JSON values are mapped
to Perl.
=back
=head1 DEPRECATED FUNCTIONS
=over
=item from_json
from_json has been renamed to decode_json
=item to_json
to_json has been renamed to encode_json
=back
=head1 A FEW NOTES ON UNICODE AND PERL
Since this often leads to confusion, here are a few very clear words on
how Unicode works in Perl, modulo bugs.
=over 4
=item 1. Perl strings can store characters with ordinal values > 255.
This enables you to store Unicode characters as single characters in a
Perl string - very natural.
=item 2. Perl does I<not> associate an encoding with your strings.
... until you force it to, e.g. when matching it against a regex, or
printing the scalar to a file, in which case Perl either interprets
your string as locale-encoded text, octets/binary, or as Unicode,
depending on various settings. In no case is an encoding stored
together with your data, it is I<use> that decides encoding, not any
magical meta data.
=item 3. The internal utf-8 flag has no meaning with regards to the
encoding of your string.
=item 4. A "Unicode String" is simply a string where each character
can be validly interpreted as a Unicode code point.
If you have UTF-8 encoded data, it is no longer a Unicode string, but
a Unicode string encoded in UTF-8, giving you a binary string.
=item 5. A string containing "high" (> 255) character values is I<not>
a UTF-8 string.
=item 6. Unicode noncharacters only warn, as in core.
The 66 Unicode noncharacters U+FDD0..U+FDEF, and U+*FFFE, U+*FFFF just
warn, see L<http://www.unicode.org/versions/corrigendum9.html>. But
illegal surrogate pairs fail to parse.
=item 7. Raw non-Unicode characters above U+10FFFF are disallowed.
Raw non-Unicode characters outside the valid unicode range fail to
parse, because "A string is a sequence of zero or more Unicode
characters" RFC 7159 section 1 and "JSON text SHALL be encoded in
Unicode RFC 7159 section 8.1. We use now the UTF8_DISALLOW_SUPER
flag when parsing unicode.
=back
I hope this helps :)
=head1 OBJECT-ORIENTED INTERFACE
The object oriented interface lets you configure your own encoding or
decoding style, within the limits of supported formats.
=over 4
=item $json = new Cpanel::JSON::XS
Creates a new JSON object that can be used to de/encode JSON
strings. All boolean flags described below are by default I<disabled>.
The mutators for flags all return the JSON object again and thus calls can
be chained:
my $json = Cpanel::JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
=> {"a": [1, 2]}
=item $json = $json->ascii ([$enable])
=item $enabled = $json->get_ascii
If C<$enable> is true (or missing), then the C<encode> method will not
generate characters outside the code range C<0..127> (which is ASCII). Any
Unicode characters outside that range will be escaped using either a
single C<\uXXXX> (BMP characters) or a double C<\uHHHH\uLLLLL> escape sequence,
as per RFC4627. The resulting encoded JSON text can be treated as a native
Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string,
or any other superset of ASCII.
If C<$enable> is false, then the C<encode> method will not escape Unicode
characters unless required by the JSON syntax or other flags. This results
in a faster and more compact format.
See also the section I<ENCODING/CODESET FLAG NOTES> later in this
document.
The main use for this flag is to produce JSON texts that can be
transmitted over a 7-bit channel, as the encoded JSON texts will not
contain any 8 bit characters.
Cpanel::JSON::XS->new->ascii (1)->encode ([chr 0x10401])
=> ["\ud801\udc01"]
=item $json = $json->latin1 ([$enable])
=item $enabled = $json->get_latin1
If C<$enable> is true (or missing), then the C<encode> method will encode
the resulting JSON text as latin1 (or ISO-8859-1), escaping any characters
outside the code range C<0..255>. The resulting string can be treated as a
latin1-encoded JSON text or a native Unicode string. The C<decode> method
will not be affected in any way by this flag, as C<decode> by default
expects Unicode, which is a strict superset of latin1.
If C<$enable> is false, then the C<encode> method will not escape Unicode
characters unless required by the JSON syntax or other flags.
See also the section I<ENCODING/CODESET FLAG NOTES> later in this
document.
The main use for this flag is efficiently encoding binary data as JSON
text, as most octets will not be escaped, resulting in a smaller encoded
size. The disadvantage is that the resulting JSON text is encoded
in latin1 (and must correctly be treated as such when storing and
transferring), a rare encoding for JSON. It is therefore most useful when
you want to store data structures known to contain binary data efficiently
in files or databases, not when talking to other JSON encoders/decoders.
Cpanel::JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
=> ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
=item $json = $json->binary ([$enable])
=item $enabled = $json = $json->get_binary
If the C<$enable> argument is true (or missing), then the C<encode>
method will not try to detect an UTF-8 encoding in any JSON string, it
will strictly interpret it as byte sequence. The result might contain
new C<\xNN> sequences, which is B<unparsable JSON>. The C<decode>
method forbids C<\uNNNN> sequences and accepts C<\xNN> and octal
C<\NNN> sequences.
There is also a special logic for perl 5.6 and utf8. 5.6 encodes any
string to utf-8 automatically when seeing a codepoint >= C<0x80> and
< C<0x100>. With the binary flag enabled decode the perl utf8 encoded
string to the original byte encoding and encode this with C<\xNN>
escapes. This will result to the same encodings as with newer
perls. But note that binary multi-byte codepoints with 5.6 will
result in C<illegal unicode character in binary string> errors,
unlike with newer perls.
If C<$enable> is false, then the C<encode> method will smartly try to
detect Unicode characters unless required by the JSON syntax or other
flags and hex and octal sequences are forbidden.
See also the section I<ENCODING/CODESET FLAG NOTES> later in this
document.
The main use for this flag is to avoid the smart unicode detection and
possible double encoding. The disadvantage is that the resulting JSON
text is encoded in new C<\xNN> and in latin1 characters and must
correctly be treated as such when storing and transferring, a rare
encoding for JSON. It will produce non-readable JSON strings in the
browser. It is therefore most useful when you want to store data
structures known to contain binary data efficiently in files or
databases, not when talking to other JSON encoders/decoders. The
binary decoding method can also be used when an encoder produced a
non-JSON conformant hex or octal encoding C<\xNN> or C<\NNN>.
Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{abc}"])
5.6: Error: malformed or illegal unicode character in binary string
>=5.8: ['\x89\xe0\xaa\xbc']
Cpanel::JSON::XS->new->binary->encode (["\x{89}\x{bc}"])
=> ["\x89\xbc"]
Cpanel::JSON::XS->new->binary->decode (["\x89\ua001"])
Error: malformed or illegal unicode character in binary string
Cpanel::JSON::XS->new->decode (["\x89"])
Error: illegal hex character in non-binary string
=item $json = $json->utf8 ([$enable])
=item $enabled = $json->get_utf8
If C<$enable> is true (or missing), then the C<encode> method will encode
the JSON result into UTF-8, as required by many protocols, while the
C<decode> method expects to be handled an UTF-8-encoded string. Please
note that UTF-8-encoded strings do not contain any characters outside the
range C<0..255>, they are thus useful for bytewise/binary I/O. In future
versions, enabling this option might enable autodetection of the UTF-16
and UTF-32 encoding families, as described in RFC4627.
If C<$enable> is false, then the C<encode> method will return the JSON
string as a (non-encoded) Unicode string, while C<decode> expects thus a
Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
to be done yourself, e.g. using the Encode module.
See also the section I<ENCODING/CODESET FLAG NOTES> later in this
document.
Example, output UTF-16BE-encoded JSON:
use Encode;
$jsontext = encode "UTF-16BE", Cpanel::JSON::XS->new->encode ($object);
Example, decode UTF-32LE-encoded JSON:
use Encode;
$object = Cpanel::JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
=item $json = $json->pretty ([$enable])
This enables (or disables) all of the C<indent>, C<space_before> and
C<space_after> (and in the future possibly more) flags in one call to
generate the most readable (or most compact) form possible.
Example, pretty-print some simple structure:
my $json = Cpanel::JSON::XS->new->pretty(1)->encode ({a => [1,2]})
=>
{
"a" : [
1,
2
]
}
=item $json = $json->indent ([$enable])
=item $enabled = $json->get_indent
If C<$enable> is true (or missing), then the C<encode> method will use
a multiline format as output, putting every array member or
object/hash key-value pair into its own line, indenting them properly.
If C<$enable> is false, no newlines or indenting will be produced, and the
resulting JSON text is guaranteed not to contain any C<newlines>.
This setting has no effect when decoding JSON texts.
=item $json = $json->indent_length([$number_of_spaces])
=item $length = $json->get_indent_length()
Set the indent length (default C<3>).
This option is only useful when you also enable indent or pretty.
The acceptable range is from 0 (no indentation) to 15
=item $json = $json->space_before ([$enable])
=item $enabled = $json->get_space_before
If C<$enable> is true (or missing), then the C<encode> method will add an extra
optional space before the C<:> separating keys from values in JSON objects.
If C<$enable> is false, then the C<encode> method will not add any extra
space at those places.
This setting has no effect when decoding JSON texts. You will also
most likely combine this setting with C<space_after>.
Example, space_before enabled, space_after and indent disabled:
{"key" :"value"}
=item $json = $json->space_after ([$enable])
=item $enabled = $json->get_space_after
If C<$enable> is true (or missing), then the C<encode> method will add
an extra optional space after the C<:> separating keys from values in
JSON objects and extra whitespace after the C<,> separating key-value
pairs and array members.
If C<$enable> is false, then the C<encode> method will not add any extra
space at those places.
This setting has no effect when decoding JSON texts.
Example, space_before and indent disabled, space_after enabled:
{"key": "value"}
=item $json = $json->relaxed ([$enable])
=item $enabled = $json->get_relaxed
If C<$enable> is true (or missing), then C<decode> will accept some
extensions to normal JSON syntax (see below). C<encode> will not be
affected in anyway. I<Be aware that this option makes you accept invalid
JSON texts as if they were valid!>. I suggest only to use this option to
parse application-specific files written by humans (configuration files,
resource files etc.)
If C<$enable> is false (the default), then C<decode> will only accept
valid JSON texts.
Currently accepted extensions are:
=over 4
=item * list items can have an end-comma
JSON I<separates> array elements and key-value pairs with commas. This
can be annoying if you write JSON texts manually and want to be able to
quickly append elements, so this extension accepts comma at the end of
such items not just between them:
[
1,
2, <- this comma not normally allowed
]
{
"k1": "v1",
"k2": "v2", <- this comma not normally allowed
}
=item * shell-style '#'-comments
Whenever JSON allows whitespace, shell-style comments are additionally
allowed. They are terminated by the first carriage-return or line-feed
character, after which more white-space and comments are allowed.
[
1, # this comment not allowed in JSON
# neither this one...
]
=item * literal ASCII TAB characters in strings
Literal ASCII TAB characters are now allowed in strings (and treated as
C<\t>) in relaxed mode. Despite JSON mandates, that TAB character is
substituted for "\t" sequence.
[
"Hello\tWorld",
"Hello<TAB>World", # literal <TAB> would not normally be allowed
]
=item * allow_singlequote
Single quotes are accepted instead of double quotes. See the
L</allow_singlequote> option.
{ "foo":'bar' }
{ 'foo':"bar" }
{ 'foo':'bar' }
=item * allow_barekey
Accept unquoted object keys instead of with mandatory double quotes. See the
L</allow_barekey> option.
{ foo:"bar" }
=item * allow_dupkeys
Allow decoding of duplicate keys in hashes. By default duplicate keys are forbidden.
See L<http://seriot.ch/projects/parsing_json.php#24>:
RFC 7159 section 4: "The names within an object should be unique."
See the C<allow_dupkeys> option.
=back
=item $json = $json->canonical ([$enable])
=item $enabled = $json->get_canonical
If C<$enable> is true (or missing), then the C<encode> method will
output JSON objects by sorting their keys. This is adding a
comparatively high overhead.
If C<$enable> is false, then the C<encode> method will output key-value
pairs in the order Perl stores them (which will likely change between runs
of the same script, and can change even within the same run from 5.18
onwards).
This option is useful if you want the same data structure to be encoded as
the same JSON text (given the same overall settings). If it is disabled,
the same hash might be encoded differently even if contains the same data,
as key-value pairs have no inherent ordering in Perl.
This setting has no effect when decoding JSON texts.
This is now also done with tied hashes, contrary to L<JSON::XS>.
But note that with most large tied hashes stored as tree it is advised to
sort the iterator already and don't sort the hash output here. Most such
iterators are already sorted, as such e.g. L<DB_File> with C<DB_BTREE>.
=item $json = $json->sort_by (undef, 0, 1 or a block)
This currently only (un)sets the C<canonical> option, and ignores
custom sort blocks.
This setting has no effect when decoding JSON texts.
This setting has currently no effect on tied hashes.
=item $json = $json->escape_slash ([$enable])
=item $enabled = $json->get_escape_slash
According to the JSON Grammar, the I<forward slash> character (U+002F)
C<"/"> need to be escaped. But by default strings are encoded without
escaping slashes in all perl JSON encoders.
If C<$enable> is true (or missing), then C<encode> will escape slashes,
C<"\/">.
This setting has no effect when decoding JSON texts.
=item $json = $json->unblessed_bool ([$enable])
=item $enabled = $json->get_unblessed_bool
$json = $json->unblessed_bool([$enable])
If C<$enable> is true (or missing), then C<decode> will return
Perl non-object boolean variables (1 and 0) for JSON booleans
(C<true> and C<false>). If C<$enable> is false, then C<decode>
will return C<JSON::PP::Boolean> objects for JSON booleans.
=item $json = $json->allow_singlequote ([$enable])
=item $enabled = $json->get_allow_singlequote
$json = $json->allow_singlequote([$enable])
If C<$enable> is true (or missing), then C<decode> will accept
JSON strings quoted by single quotations that are invalid JSON
format.
$json->allow_singlequote->decode({"foo":'bar'});
$json->allow_singlequote->decode({'foo':"bar"});
$json->allow_singlequote->decode({'foo':'bar'});
This is also enabled with C<relaxed>.
As same as the C<relaxed> option, this option may be used to parse
application-specific files written by humans.
=item $json = $json->allow_barekey ([$enable])
=item $enabled = $json->get_allow_barekey
$json = $json->allow_barekey([$enable])
If C<$enable> is true (or missing), then C<decode> will accept
bare keys of JSON object that are invalid JSON format.
Same as with the C<relaxed> option, this option may be used to parse
application-specific files written by humans.
$json->allow_barekey->decode('{foo:"bar"}');
=item $json = $json->allow_bignum ([$enable])
=item $enabled = $json->get_allow_bignum
$json = $json->allow_bignum([$enable])
If C<$enable> is true (or missing), then C<decode> will convert
the big integer Perl cannot handle as integer into a L<Math::BigInt>
object and convert a floating number (any) into a L<Math::BigFloat>.
On the contrary, C<encode> converts C<Math::BigInt> objects and
C<Math::BigFloat> objects into JSON numbers with C<allow_blessed>
enable.
$json->allow_nonref->allow_blessed->allow_bignum;
$bigfloat = $json->decode('2.000000000000000000000000001');
print $json->encode($bigfloat);
# => 2.000000000000000000000000001
See L</MAPPING> about the normal conversion of JSON number.
=item $json = $json->allow_bigint ([$enable])
This option is obsolete and replaced by allow_bignum.
=item $json = $json->allow_nonref ([$enable])
=item $enabled = $json->get_allow_nonref
If C<$enable> is true (or missing), then the C<encode> method can
convert a non-reference into its corresponding string, number or null
JSON value, which is an extension to RFC4627. Likewise, C<decode> will
accept those JSON values instead of croaking.
If C<$enable> is false, then the C<encode> method will croak if it isn't
passed an arrayref or hashref, as JSON texts must either be an object
or array. Likewise, C<decode> will croak if given something that is not a
JSON object or array.
Example, encode a Perl scalar as JSON value with enabled C<allow_nonref>,
resulting in an invalid JSON text:
Cpanel::JSON::XS->new->allow_nonref->encode ("Hello, World!")
=> "Hello, World!"
=item $json = $json->allow_unknown ([$enable])
=item $enabled = $json->get_allow_unknown
If C<$enable> is true (or missing), then C<encode> will I<not> throw an
exception when it encounters values it cannot represent in JSON (for
example, filehandles) but instead will encode a JSON C<null> value. Note
that blessed objects are not included here and are handled separately by
c<allow_nonref>.
If C<$enable> is false (the default), then C<encode> will throw an
exception when it encounters anything it cannot encode as JSON.
This option does not affect C<decode> in any way, and it is recommended to
leave it off unless you know your communications partner.
=item $json = $json->allow_stringify ([$enable])
=item $enabled = $json->get_allow_stringify
If C<$enable> is true (or missing), then C<encode> will stringify the
non-object perl value or reference. Note that blessed objects are not
included here and are handled separately by C<allow_blessed> and
C<convert_blessed>. String references are stringified to the string
value, other references as in perl.
This option does not affect C<decode> in any way.
This option is special to this module, it is not supported by other
encoders. So it is not recommended to use it.
=item $json = $json->require_types ([$enable])
=item $enable = $json->get_require_types
$json = $json->require_types([$enable])
If C<$enable> is true (or missing), then C<encode> will require
either enabled C<type_all_string> or second argument with supplied JSON types.
See L<Cpanel::JSON::XS::Type>. When C<type_all_string> is not enabled or
second argument is not provided (or is undef), then C<encode>
croaks. It also croaks when the type for provided structure in
C<encode> is incomplete.
=item $json = $json->type_all_string ([$enable])
=item $enable = $json->get_type_all_string
$json = $json->type_all_string([$enable])
If C<$enable> is true (or missing), then C<encode> will always
produce stable deterministic JSON string types in resulted output.
When C<$enable> is false, then result of encoded JSON output may be
different for different Perl versions and may depends on loaded modules.
This is useful it you need deterministic JSON types, independently of used
Perl version and other modules, but do not want to write complicated type
definitions for L<Cpanel::JSON::XS::Type>.
=item $json = $json->allow_dupkeys ([$enable])
=item $enabled = $json->get_allow_dupkeys
If C<$enable> is true (or missing), then the C<decode> method will not
die when it encounters duplicate keys in a hash.
C<allow_dupkeys> is also enabled in the C<relaxed> mode.
The JSON spec allows duplicate name in objects but recommends to
disable it, however with Perl hashes they are impossible, parsing
JSON in Perl silently ignores duplicate names, using the last value
found.
See L<http://seriot.ch/projects/parsing_json.php#24>:
RFC 7159 section 4: "The names within an object should be unique."
=item $json = $json->dupkeys_as_arrayref ([$enable])
=item $enabled = $json->get_dupkeys_as_arrayref
If enabled, allow decoding of duplicate keys in hashes and store the
values as arrayref in the hash instead. By default duplicate keys are
forbidden. Enabling this also enables the L</allow_dupkeys> option,
but disabling this does not disable the L</allow_dupkeys> option.
Example:
$json->dupkeys_as_arrayref;
print encode_json ($json->decode ('{"a":"b","a":"c"}'));
=> {"a":["b","c"]}
This changes the result structure, thus cannot be enabled by default.
The client must be aware of it. The resulting arrayref is not yet marked somehow
(blessed or such).
=item $json = $json->allow_blessed ([$enable])
=item $enabled = $json->get_allow_blessed
If C<$enable> is true (or missing), then the C<encode> method will not
barf when it encounters a blessed reference. Instead, the value of the
B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
disabled or no C<TO_JSON> method found) or a representation of the
object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
encoded. Has no effect on C<decode>.
If C<$enable> is false (the default), then C<encode> will throw an
exception when it encounters a blessed object without C<convert_blessed>
and a C<TO_JSON> method.
This setting has no effect on C<decode>.
=item $json = $json->convert_blessed ([$enable])
=item $enabled = $json->get_convert_blessed
If C<$enable> is true (or missing), then C<encode>, upon encountering a
blessed object, will check for the availability of the C<TO_JSON> method
on the object's class. If found, it will be called in scalar context
and the resulting scalar will be encoded instead of the object. If no
C<TO_JSON> method is found, a stringification overload method is tried next.
If both are not found, the value of C<allow_blessed> will decide what
to do.
The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
returns other blessed objects, those will be handled in the same
way. C<TO_JSON> must take care of not causing an endless recursion
cycle (== crash) in this case. The same care must be taken with
calling encode in stringify overloads (even if this works by luck in
older perls) or other callbacks. The name of C<TO_JSON> was chosen
because other methods called by the Perl core (== not by the user of
the object) are usually in upper case letters and to avoid collisions
with any C<to_json> function or method.
If C<$enable> is false (the default), then C<encode> will not consider
this type of conversion.
This setting has no effect on C<decode>.
=item $json = $json->allow_tags ([$enable])
=item $enabled = $json->get_allow_tags
See L<OBJECT SERIALIZATION> for details.
If C<$enable> is true (or missing), then C<encode>, upon encountering a
blessed object, will check for the availability of the C<FREEZE> method on
the object's class. If found, it will be used to serialize the object into
a nonstandard tagged JSON value (that JSON decoders cannot decode).
It also causes C<decode> to parse such tagged JSON values and deserialize
them via a call to the C<THAW> method.
If C<$enable> is false (the default), then C<encode> will not consider
this type of conversion, and tagged JSON values will cause a parse error
in C<decode>, as if tags were not part of the grammar.
=item $json = $json->filter_json_object ([$coderef->($hashref)])
When C<$coderef> is specified, it will be called from C<decode> each
time it decodes a JSON object. The only argument is a reference to the
newly-created hash. If the code references returns a single scalar (which
need not be a reference), this value (i.e. a copy of that scalar to avoid
aliasing) is inserted into the deserialized data structure. If it returns
an empty list (NOTE: I<not> C<undef>, which is a valid scalar), the
original deserialized hash will be inserted. This setting can slow down
decoding considerably.
When C<$coderef> is omitted or undefined, any existing callback will
be removed and C<decode> will not change the deserialized hash in any
way.
Example, convert all JSON objects into the integer 5:
my $js = Cpanel::JSON::XS->new->filter_json_object (sub { 5 });
# returns [5]
$js->decode ('[{}]')
# throw an exception because allow_nonref is not enabled
# so a lone 5 is not allowed.
$js->decode ('{"a":1, "b":2}');