.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "XS 3pm" .TH XS 3pm "2014-04-26" "perl v5.20.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Cpanel::JSON::XS \- JSON::XS for Cpanel, fast and correct serialising, also for 5.6.2 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& 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. .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module converts Perl data structures to \s-1JSON\s0 and vice versa. Its primary goal is to be \fIcorrect\fR and its secondary goal is to be \&\fIfast\fR. To reach the latter goal it was written in C. .PP As this is the n\-th-something \s-1JSON\s0 module on \s-1CPAN,\s0 what was the reason to write yet another \s-1JSON\s0 module? While it seems there are many \s-1JSON\s0 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. .PP See below for the Cpanel fork. .PP See \s-1MAPPING,\s0 below, on how Cpanel::JSON::XS maps perl values to \s-1JSON\s0 values and vice versa. .SS "\s-1FEATURES\s0" .IX Subsection "FEATURES" .IP "\(bu" 4 smart Unicode handling .Sp 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 \*(L"correct\*(R" means. .IP "\(bu" 4 round-trip integrity .Sp When you serialise a perl data structure using only data types supported by \s-1JSON\s0 and Perl, the deserialised data structure is identical on the Perl level. (e.g. the string \*(L"2.0\*(R" doesn't suddenly become \*(L"2\*(R" just because it looks like a number). There \fIare\fR minor exceptions to this, read the \&\s-1MAPPING\s0 section below to learn about those. .IP "\(bu" 4 strict checking of \s-1JSON\s0 correctness .Sp There is no guessing, no generating of illegal \s-1JSON\s0 texts by default, and only \s-1JSON\s0 is accepted as input by default (the latter is a security feature). .IP "\(bu" 4 fast .Sp Compared to other \s-1JSON\s0 modules and other serialisers such as Storable, this module usually compares favourably in terms of speed, too. .IP "\(bu" 4 simple to use .Sp This module has both a simple functional interface as well as an object oriented interface. .IP "\(bu" 4 reasonably versatile output formats .Sp 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. .SS "cPanel fork" .IX Subsection "cPanel fork" Since the original author \s-1MLEHMANN\s0 has no public bugtracker, this cPanel fork sits now on github. .PP src repo: original: .PP \&\s-1RT: \s0 or .PP \&\fBChanges to \s-1JSON::XS\s0\fR .PP \&\- added \f(CW\*(C`binary\*(C'\fR extension, non-JSON and non \s-1JSON\s0 parsable, allows \f(CW\*(C`\exNN\*(C'\fR and \f(CW\*(C`\eNNN\*(C'\fR sequences. .PP \&\- 5.6.2 support; sacrificing some utf8 features (assuming bytes all-over), no multi-byte unicode characters. .PP \&\- interop for true/false overloading. \s-1JSON::XS\s0 and \s-1JSON::PP\s0 representations are accepted and \s-1JSON::XS\s0 accepts Cpanel::JSON::XS booleans [#13] .PP \&\- ithread support. Cpanel::JSON::XS is thread-safe, \s-1JSON::XS\s0 not .PP \&\- performance optimizations for threaded Perls .PP \&\- additional fixes for: .PP .Vb 1 \& \- [cpan #88061] AIX atof without USE_LONG_DOUBLE \& \& \- #10 unshare_hek crash \& \& \- #7 avoid re\-blessing where possible (e.g. SvREADONLY restricted hashes) .Ve .PP \&\- public maintenance and bugtracker .PP \&\- use ppport.h, sanify \s-1XS\s0.xs comment styles, harness C coding style .PP \&\- common::sense is optional. When available it is not used in the published production module, just during development and testing. .PP \&\- extended testsuite .SH "FUNCTIONAL INTERFACE" .IX Header "FUNCTIONAL INTERFACE" The following convenience methods are provided by this module. They are exported by default: .ie n .IP "$json_text = encode_json $perl_scalar" 4 .el .IP "\f(CW$json_text\fR = encode_json \f(CW$perl_scalar\fR" 4 .IX Item "$json_text = encode_json $perl_scalar" Converts the given Perl data structure to a \s-1UTF\-8\s0 encoded, binary string (that is, the string contains octets only). Croaks on error. .Sp This function call is functionally identical to: .Sp .Vb 1 \& $json_text = Cpanel::JSON::XS\->new\->utf8\->encode ($perl_scalar) .Ve .Sp Except being faster. .ie n .IP "$perl_scalar = decode_json $json_text" 4 .el .IP "\f(CW$perl_scalar\fR = decode_json \f(CW$json_text\fR" 4 .IX Item "$perl_scalar = decode_json $json_text" The opposite of \f(CW\*(C`encode_json\*(C'\fR: expects an \s-1UTF\-8 \s0(binary) string and tries to parse that as an \s-1UTF\-8\s0 encoded \s-1JSON\s0 text, returning the resulting reference. Croaks on error. .Sp This function call is functionally identical to: .Sp .Vb 1 \& $perl_scalar = Cpanel::JSON::XS\->new\->utf8\->decode ($json_text) .Ve .Sp Except being faster. .ie n .IP "$is_boolean = Cpanel::JSON::XS::is_bool $scalar" 4 .el .IP "\f(CW$is_boolean\fR = Cpanel::JSON::XS::is_bool \f(CW$scalar\fR" 4 .IX Item "$is_boolean = Cpanel::JSON::XS::is_bool $scalar" Returns true if the passed scalar represents either Cpanel::JSON::XS::true or Cpanel::JSON::XS::false, two constants that act like \f(CW1\fR and \f(CW0\fR, respectively and are used to represent \s-1JSON \s0\f(CW\*(C`true\*(C'\fR and \f(CW\*(C`false\*(C'\fR values in Perl. .Sp See \s-1MAPPING,\s0 below, for more information on how \s-1JSON\s0 values are mapped to Perl. .SH "DEPRECATED FUNCTIONS" .IX Header "DEPRECATED FUNCTIONS" .IP "from_json" 4 .IX Item "from_json" from_json has been renamed to encode_json .IP "to_json" 4 .IX Item "to_json" to_json has been renamed to encode_json .SH "A FEW NOTES ON UNICODE AND PERL" .IX Header "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. .IP "1. Perl strings can store characters with ordinal values > 255." 4 .IX 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. .IP "2. Perl does \fInot\fR associate an encoding with your strings." 4 .IX Item "2. Perl does 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 \fIuse\fR that decides encoding, not any magical meta data. .IP "3. The internal utf\-8 flag has no meaning with regards to the encoding of your string." 4 .IX Item "3. The internal utf-8 flag has no meaning with regards to the encoding of your string." .PD 0 .ie n .IP "4. A ""Unicode String"" is simply a string where each character can be validly interpreted as a Unicode code point." 4 .el .IP "4. A ``Unicode String'' is simply a string where each character can be validly interpreted as a Unicode code point." 4 .IX Item "4. A Unicode String is simply a string where each character can be validly interpreted as a Unicode code point." .PD If you have \s-1UTF\-8\s0 encoded data, it is no longer a Unicode string, but a Unicode string encoded in \s-1UTF\-8,\s0 giving you a binary string. .ie n .IP "5. A string containing ""high"" (> 255) character values is \fInot\fR a \s-1UTF\-8\s0 string." 4 .el .IP "5. A string containing ``high'' (> 255) character values is \fInot\fR a \s-1UTF\-8\s0 string." 4 .IX Item "5. A string containing high (> 255) character values is not a UTF-8 string." .PP I hope this helps :) .SH "OBJECT-ORIENTED INTERFACE" .IX Header "OBJECT-ORIENTED INTERFACE" The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats. .ie n .IP "$json = new Cpanel::JSON::XS" 4 .el .IP "\f(CW$json\fR = new Cpanel::JSON::XS" 4 .IX Item "$json = new Cpanel::JSON::XS" Creates a new \s-1JSON\s0 object that can be used to de/encode \s-1JSON\s0 strings. All boolean flags described below are by default \fIdisabled\fR. .Sp The mutators for flags all return the \s-1JSON\s0 object again and thus calls can be chained: .Sp .Vb 2 \& my $json = Cpanel::JSON::XS\->new\->utf8\->space_after\->encode ({a => [1,2]}) \& => {"a": [1, 2]} .Ve .ie n .IP "$json = $json\->ascii ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->ascii ([$enable])" 4 .IX Item "$json = $json->ascii ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_ascii" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_ascii" 4 .IX Item "$enabled = $json->get_ascii" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will not generate characters outside the code range \f(CW0..127\fR (which is \s-1ASCII\s0). Any Unicode characters outside that range will be escaped using either a single \euXXXX (\s-1BMP\s0 characters) or a double \euHHHH\euLLLLL escape sequence, as per \s-1RFC4627.\s0 The resulting encoded \s-1JSON\s0 text can be treated as a native Unicode string, an ascii-encoded, latin1\-encoded or \s-1UTF\-8\s0 encoded string, or any other superset of \s-1ASCII.\s0 .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not escape Unicode characters unless required by the \s-1JSON\s0 syntax or other flags. This results in a faster and more compact format. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp The main use for this flag is to produce \s-1JSON\s0 texts that can be transmitted over a 7\-bit channel, as the encoded \s-1JSON\s0 texts will not contain any 8 bit characters. .Sp .Vb 2 \& Cpanel::JSON::XS\->new\->ascii (1)\->encode ([chr 0x10401]) \& => ["\eud801\eudc01"] .Ve .ie n .IP "$json = $json\->latin1 ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->latin1 ([$enable])" 4 .IX Item "$json = $json->latin1 ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_latin1" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_latin1" 4 .IX Item "$enabled = $json->get_latin1" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will encode the resulting \s-1JSON\s0 text as latin1 (or iso\-8859\-1), escaping any characters outside the code range \f(CW0..255\fR. The resulting string can be treated as a latin1\-encoded \s-1JSON\s0 text or a native Unicode string. The \f(CW\*(C`decode\*(C'\fR method will not be affected in any way by this flag, as \f(CW\*(C`decode\*(C'\fR by default expects Unicode, which is a strict superset of latin1. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not escape Unicode characters unless required by the \s-1JSON\s0 syntax or other flags. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp The main use for this flag is efficiently encoding binary data as \s-1JSON\s0 text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting \s-1JSON\s0 text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for \s-1JSON.\s0 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 \s-1JSON\s0 encoders/decoders. .Sp .Vb 2 \& Cpanel::JSON::XS\->new\->latin1\->encode (["\ex{89}\ex{abc}"] \& => ["\ex{89}\e\eu0abc"] # (perl syntax, U+abc escaped, U+89 not) .Ve .ie n .IP "$json = $json\->binary ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->binary ([$enable])" 4 .IX Item "$json = $json->binary ([$enable])" .PD 0 .ie n .IP "$enabled = $json = $json\->get_binary" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR = \f(CW$json\fR\->get_binary" 4 .IX Item "$enabled = $json = $json->get_binary" .PD If the \f(CW$enable\fR argument is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will not try to detect an \s-1UTF\-8\s0 encoding in any \s-1JSON\s0 string, it will strictly interpret it as byte sequence. The result might contain new \f(CW\*(C`\exNN\*(C'\fR sequences, which is \fBunparsable \s-1JSON\s0\fR. The \f(CW\*(C`decode\*(C'\fR method forbids \f(CW\*(C`\euNNNN\*(C'\fR sequences and accepts \f(CW\*(C`\exNN\*(C'\fR and octal \f(CW\*(C`\eNNN\*(C'\fR sequences. .Sp 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 >= \f(CW0x80\fR and < \f(CW0x100\fR. With the binary flag enabled decode the perl utf8 encoded string to the original byte encoding and encode this with \f(CW\*(C`\exNN\*(C'\fR 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 \f(CW\*(C`illegal unicode character in binary string\*(C'\fR errors, unlike with newer perls. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will smartly try to detect Unicode characters unless required by the \s-1JSON\s0 syntax or other flags and hex and octal sequences are forbidden. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp The main use for this flag is to avoid the smart unicode detection and possible double encoding. The disadvantage is that the resulting \s-1JSON\s0 text is encoded in new \f(CW\*(C`\exNN\*(C'\fR and in latin1 characters and must correctly be treated as such when storing and transferring, a rare encoding for \s-1JSON.\s0 It will produce non-readable \s-1JSON\s0 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 \s-1JSON\s0 encoders/decoders. The binary decoding method can also be used when an encoder produced a non-JSON conformant hex or octal encoding \f(CW\*(C`\exNN\*(C'\fR or \f(CW\*(C`\eNNN\*(C'\fR. .Sp .Vb 3 \& Cpanel::JSON::XS\->new\->binary\->encode (["\ex{89}\ex{abc}"]) \& 5.6: Error: malformed or illegal unicode character in binary string \& >=5.8: [\*(Aq\ex89\exe0\exaa\exbc\*(Aq] \& \& Cpanel::JSON::XS\->new\->binary\->encode (["\ex{89}\ex{bc}"]) \& => ["\ex89\exbc"] \& \& Cpanel::JSON::XS\->new\->binary\->decode (["\ex89\eua001"]) \& Error: malformed or illegal unicode character in binary string \& \& Cpanel::JSON::XS\->new\->decode (["\ex89"]) \& Error: illegal hex character in non\-binary string .Ve .ie n .IP "$json = $json\->utf8 ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->utf8 ([$enable])" 4 .IX Item "$json = $json->utf8 ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_utf8" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_utf8" 4 .IX Item "$enabled = $json->get_utf8" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will encode the \s-1JSON\s0 result into \s-1UTF\-8,\s0 as required by many protocols, while the \&\f(CW\*(C`decode\*(C'\fR 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 \f(CW0..255\fR, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the \s-1UTF\-16\s0 and \s-1UTF\-32\s0 encoding families, as described in \s-1RFC4627.\s0 .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will return the \s-1JSON\s0 string as a (non-encoded) Unicode string, while \f(CW\*(C`decode\*(C'\fR expects thus a Unicode string. Any decoding or encoding (e.g. to \s-1UTF\-8\s0 or \s-1UTF\-16\s0) needs to be done yourself, e.g. using the Encode module. .Sp See also the section \fI\s-1ENCODING/CODESET FLAG NOTES\s0\fR later in this document. .Sp Example, output UTF\-16BE\-encoded \s-1JSON:\s0 .Sp .Vb 2 \& use Encode; \& $jsontext = encode "UTF\-16BE", Cpanel::JSON::XS\->new\->encode ($object); .Ve .Sp Example, decode UTF\-32LE\-encoded \s-1JSON:\s0 .Sp .Vb 2 \& use Encode; \& $object = Cpanel::JSON::XS\->new\->decode (decode "UTF\-32LE", $jsontext); .Ve .ie n .IP "$json = $json\->pretty ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->pretty ([$enable])" 4 .IX Item "$json = $json->pretty ([$enable])" This enables (or disables) all of the \f(CW\*(C`indent\*(C'\fR, \f(CW\*(C`space_before\*(C'\fR and \&\f(CW\*(C`space_after\*(C'\fR (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible. .Sp Example, pretty-print some simple structure: .Sp .Vb 8 \& my $json = Cpanel::JSON::XS\->new\->pretty(1)\->encode ({a => [1,2]}) \& => \& { \& "a" : [ \& 1, \& 2 \& ] \& } .Ve .ie n .IP "$json = $json\->indent ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->indent ([$enable])" 4 .IX Item "$json = $json->indent ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_indent" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_indent" 4 .IX Item "$enabled = $json->get_indent" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR 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. .Sp If \f(CW$enable\fR is false, no newlines or indenting will be produced, and the resulting \s-1JSON\s0 text is guaranteed not to contain any \f(CW\*(C`newlines\*(C'\fR. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. .ie n .IP "$json = $json\->space_before ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->space_before ([$enable])" 4 .IX Item "$json = $json->space_before ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_space_before" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_space_before" 4 .IX Item "$enabled = $json->get_space_before" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will add an extra optional space before the \f(CW\*(C`:\*(C'\fR separating keys from values in \s-1JSON\s0 objects. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not add any extra space at those places. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. You will also most likely combine this setting with \f(CW\*(C`space_after\*(C'\fR. .Sp Example, space_before enabled, space_after and indent disabled: .Sp .Vb 1 \& {"key" :"value"} .Ve .ie n .IP "$json = $json\->space_after ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->space_after ([$enable])" 4 .IX Item "$json = $json->space_after ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_space_after" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_space_after" 4 .IX Item "$enabled = $json->get_space_after" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will add an extra optional space after the \f(CW\*(C`:\*(C'\fR separating keys from values in \s-1JSON\s0 objects and extra whitespace after the \f(CW\*(C`,\*(C'\fR separating key-value pairs and array members. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will not add any extra space at those places. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. .Sp Example, space_before and indent disabled, space_after enabled: .Sp .Vb 1 \& {"key": "value"} .Ve .ie n .IP "$json = $json\->relaxed ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->relaxed ([$enable])" 4 .IX Item "$json = $json->relaxed ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_relaxed" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_relaxed" 4 .IX Item "$enabled = $json->get_relaxed" .PD If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`decode\*(C'\fR will accept some extensions to normal \s-1JSON\s0 syntax (see below). \f(CW\*(C`encode\*(C'\fR will not be affected in anyway. \fIBe aware that this option makes you accept invalid \&\s-1JSON\s0 texts as if they were valid!\fR. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.) .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`decode\*(C'\fR will only accept valid \s-1JSON\s0 texts. .Sp Currently accepted extensions are: .RS 4 .IP "\(bu" 4 list items can have an end-comma .Sp \&\s-1JSON \s0\fIseparates\fR array elements and key-value pairs with commas. This can be annoying if you write \s-1JSON\s0 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: .Sp .Vb 8 \& [ \& 1, \& 2, <\- this comma not normally allowed \& ] \& { \& "k1": "v1", \& "k2": "v2", <\- this comma not normally allowed \& } .Ve .IP "\(bu" 4 shell-style '#'\-comments .Sp Whenever \s-1JSON\s0 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. .Sp .Vb 4 \& [ \& 1, # this comment not allowed in JSON \& # neither this one... \& ] .Ve .RE .RS 4 .RE .ie n .IP "$json = $json\->canonical ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->canonical ([$enable])" 4 .IX Item "$json = $json->canonical ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_canonical" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_canonical" 4 .IX Item "$enabled = $json->get_canonical" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will output \s-1JSON\s0 objects by sorting their keys. This is adding a comparatively high overhead. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script). .Sp This option is useful if you want the same data structure to be encoded as the same \s-1JSON\s0 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. .Sp This setting has no effect when decoding \s-1JSON\s0 texts. .Sp This setting has currently no effect on tied hashes. .ie n .IP "$json = $json\->allow_nonref ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_nonref ([$enable])" 4 .IX Item "$json = $json->allow_nonref ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_nonref" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_nonref" 4 .IX Item "$enabled = $json->get_allow_nonref" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method can convert a non-reference into its corresponding string, number or null \s-1JSON\s0 value, which is an extension to \s-1RFC4627.\s0 Likewise, \f(CW\*(C`decode\*(C'\fR will accept those \s-1JSON\s0 values instead of croaking. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`encode\*(C'\fR method will croak if it isn't passed an arrayref or hashref, as \s-1JSON\s0 texts must either be an object or array. Likewise, \f(CW\*(C`decode\*(C'\fR will croak if given something that is not a \&\s-1JSON\s0 object or array. .Sp Example, encode a Perl scalar as \s-1JSON\s0 value with enabled \f(CW\*(C`allow_nonref\*(C'\fR, resulting in an invalid \s-1JSON\s0 text: .Sp .Vb 2 \& Cpanel::JSON::XS\->new\->allow_nonref\->encode ("Hello, World!") \& => "Hello, World!" .Ve .ie n .IP "$json = $json\->allow_unknown ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_unknown ([$enable])" 4 .IX Item "$json = $json->allow_unknown ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_unknown" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_unknown" 4 .IX Item "$enabled = $json->get_allow_unknown" .PD If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`encode\*(C'\fR will \fInot\fR throw an exception when it encounters values it cannot represent in \s-1JSON \s0(for example, filehandles) but instead will encode a \s-1JSON \s0\f(CW\*(C`null\*(C'\fR value. Note that blessed objects are not included here and are handled separately by c. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will throw an exception when it encounters anything it cannot encode as \s-1JSON.\s0 .Sp This option does not affect \f(CW\*(C`decode\*(C'\fR in any way, and it is recommended to leave it off unless you know your communications partner. .ie n .IP "$json = $json\->allow_blessed ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_blessed ([$enable])" 4 .IX Item "$json = $json->allow_blessed ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_blessed" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_blessed" 4 .IX Item "$enabled = $json->get_allow_blessed" .PD If \f(CW$enable\fR is true (or missing), then the \f(CW\*(C`encode\*(C'\fR method will not barf when it encounters a blessed reference. Instead, the value of the \&\fBconvert_blessed\fR option will decide whether \f(CW\*(C`null\*(C'\fR (\f(CW\*(C`convert_blessed\*(C'\fR disabled or no \f(CW\*(C`TO_JSON\*(C'\fR method found) or a representation of the object (\f(CW\*(C`convert_blessed\*(C'\fR enabled and \f(CW\*(C`TO_JSON\*(C'\fR method found) is being encoded. Has no effect on \f(CW\*(C`decode\*(C'\fR. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will throw an exception when it encounters a blessed object. .ie n .IP "$json = $json\->convert_blessed ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->convert_blessed ([$enable])" 4 .IX Item "$json = $json->convert_blessed ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_convert_blessed" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_convert_blessed" 4 .IX Item "$enabled = $json->get_convert_blessed" .PD If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`encode\*(C'\fR, upon encountering a blessed object, will check for the availability of the \f(CW\*(C`TO_JSON\*(C'\fR 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 \&\f(CW\*(C`TO_JSON\*(C'\fR method is found, the value of \f(CW\*(C`allow_blessed\*(C'\fR will decide what to do. .Sp The \f(CW\*(C`TO_JSON\*(C'\fR method may safely call die if it wants. If \f(CW\*(C`TO_JSON\*(C'\fR returns other blessed objects, those will be handled in the same way. \f(CW\*(C`TO_JSON\*(C'\fR must take care of not causing an endless recursion cycle (== crash) in this case. The name of \f(CW\*(C`TO_JSON\*(C'\fR 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 \f(CW\*(C`to_json\*(C'\fR function or method. .Sp This setting does not yet influence \f(CW\*(C`decode\*(C'\fR in any way, but in the future, global hooks might get installed that influence \f(CW\*(C`decode\*(C'\fR and are enabled by this setting. .Sp If \f(CW$enable\fR is false, then the \f(CW\*(C`allow_blessed\*(C'\fR setting will decide what to do when a blessed object is found. .ie n .IP "$json = $json\->allow_tags ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->allow_tags ([$enable])" 4 .IX Item "$json = $json->allow_tags ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_allow_tags" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_allow_tags" 4 .IX Item "$enabled = $json->get_allow_tags" .PD See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0 for details. .Sp If \f(CW$enable\fR is true (or missing), then \f(CW\*(C`encode\*(C'\fR, upon encountering a blessed object, will check for the availability of the \f(CW\*(C`FREEZE\*(C'\fR method on the object's class. If found, it will be used to serialise the object into a nonstandard tagged \s-1JSON\s0 value (that \s-1JSON\s0 decoders cannot decode). .Sp It also causes \f(CW\*(C`decode\*(C'\fR to parse such tagged \s-1JSON\s0 values and deserialise them via a call to the \f(CW\*(C`THAW\*(C'\fR method. .Sp If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will not consider this type of conversion, and tagged \s-1JSON\s0 values will cause a parse error in \f(CW\*(C`decode\*(C'\fR, as if tags were not part of the grammar. .ie n .IP "$json = $json\->filter_json_object ([$coderef\->($hashref)])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->filter_json_object ([$coderef\->($hashref)])" 4 .IX Item "$json = $json->filter_json_object ([$coderef->($hashref)])" When \f(CW$coderef\fR is specified, it will be called from \f(CW\*(C`decode\*(C'\fR each time it decodes a \s-1JSON\s0 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 deserialised data structure. If it returns an empty list (\s-1NOTE: \s0\fInot\fR \f(CW\*(C`undef\*(C'\fR, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably. .Sp When \f(CW$coderef\fR is omitted or undefined, any existing callback will be removed and \f(CW\*(C`decode\*(C'\fR will not change the deserialised hash in any way. .Sp Example, convert all \s-1JSON\s0 objects into the integer 5: .Sp .Vb 6 \& my $js = Cpanel::JSON::XS\->new\->filter_json_object (sub { 5 }); \& # returns [5] \& $js\->decode (\*(Aq[{}]\*(Aq) \& # throw an exception because allow_nonref is not enabled \& # so a lone 5 is not allowed. \& $js\->decode (\*(Aq{"a":1, "b":2}\*(Aq); .Ve .ie n .IP "$json = $json\->filter_json_single_key_object ($key [=> $coderef\->($value)])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->filter_json_single_key_object ($key [=> \f(CW$coderef\fR\->($value)])" 4 .IX Item "$json = $json->filter_json_single_key_object ($key [=> $coderef->($value)])" Works remotely similar to \f(CW\*(C`filter_json_object\*(C'\fR, but is only called for \&\s-1JSON\s0 objects having a single key named \f(CW$key\fR. .Sp This \f(CW$coderef\fR is called before the one specified via \&\f(CW\*(C`filter_json_object\*(C'\fR, if any. It gets passed the single value in the \s-1JSON\s0 object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even \f(CW\*(C`undef\*(C'\fR but the empty list), the callback from \f(CW\*(C`filter_json_object\*(C'\fR will be called next, as if no single-key callback were specified. .Sp If \f(CW$coderef\fR is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key. .Sp As this callback gets called less often then the \f(CW\*(C`filter_json_object\*(C'\fR one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialise Perl objects into, especially as single-key \s-1JSON\s0 objects are as close to the type-tagged value concept as \s-1JSON\s0 gets (it's basically an \s-1ID/VALUE\s0 tuple). Of course, \s-1JSON\s0 does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash. .Sp Typical names for the single object key are \f(CW\*(C`_\|_class_whatever_\|_\*(C'\fR, or \&\f(CW\*(C`$_\|_dollars_are_rarely_used_\|_$\*(C'\fR or \f(CW\*(C`}ugly_brace_placement\*(C'\fR, or even things like \f(CW\*(C`_\|_class_md5sum(classname)_\|_\*(C'\fR, to reduce the risk of clashing with real hashes. .Sp Example, decode \s-1JSON\s0 objects of the form \f(CW\*(C`{ "_\|_widget_\|_" => }\*(C'\fR into the corresponding \f(CW$WIDGET{}\fR object: .Sp .Vb 7 \& # return whatever is in $WIDGET{5}: \& Cpanel::JSON::XS \& \->new \& \->filter_json_single_key_object (_\|_widget_\|_ => sub { \& $WIDGET{ $_[0] } \& }) \& \->decode (\*(Aq{"_\|_widget_\|_": 5\*(Aq) \& \& # this can be used with a TO_JSON method in some "widget" class \& # for serialisation to json: \& sub WidgetBase::TO_JSON { \& my ($self) = @_; \& \& unless ($self\->{id}) { \& $self\->{id} = ..get..some..id..; \& $WIDGET{$self\->{id}} = $self; \& } \& \& { _\|_widget_\|_ => $self\->{id} } \& } .Ve .ie n .IP "$json = $json\->shrink ([$enable])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->shrink ([$enable])" 4 .IX Item "$json = $json->shrink ([$enable])" .PD 0 .ie n .IP "$enabled = $json\->get_shrink" 4 .el .IP "\f(CW$enabled\fR = \f(CW$json\fR\->get_shrink" 4 .IX Item "$enabled = $json->get_shrink" .PD Perl usually over-allocates memory a bit when allocating space for strings. This flag optionally resizes strings generated by either \&\f(CW\*(C`encode\*(C'\fR or \f(CW\*(C`decode\*(C'\fR to their minimum size possible. This can save memory when your \s-1JSON\s0 texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less space in general (and some buggy Perl or C code might even rely on that internal representation being used). .Sp The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time. .Sp If \f(CW$enable\fR is true (or missing), the string returned by \f(CW\*(C`encode\*(C'\fR will be shrunk-to-fit, while all strings generated by \f(CW\*(C`decode\*(C'\fR will also be shrunk-to-fit. .Sp If \f(CW$enable\fR is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster. .Sp In the future, this setting might control other things, such as converting strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space. .ie n .IP "$json = $json\->max_depth ([$maximum_nesting_depth])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->max_depth ([$maximum_nesting_depth])" 4 .IX Item "$json = $json->max_depth ([$maximum_nesting_depth])" .PD 0 .ie n .IP "$max_depth = $json\->get_max_depth" 4 .el .IP "\f(CW$max_depth\fR = \f(CW$json\fR\->get_max_depth" 4 .IX Item "$max_depth = $json->get_max_depth" .PD Sets the maximum nesting level (default \f(CW512\fR) accepted while encoding or decoding. If a higher nesting level is detected in \s-1JSON\s0 text or a Perl data structure, then the encoder and decoder will stop and croak at that point. .Sp Nesting level is defined by number of hash\- or arrayrefs that the encoder needs to traverse to reach a given point or the number of \f(CW\*(C`{\*(C'\fR or \f(CW\*(C`[\*(C'\fR characters without their matching closing parenthesis crossed to reach a given character in a string. .Sp Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array. .Sp If no argument is given, the highest possible setting will be used, which is rarely useful. .Sp Note that nesting is implemented by recursion in C. The default value has been chosen to be as large as typical operating systems allow without crashing. .Sp See \s-1SECURITY CONSIDERATIONS,\s0 below, for more info on why this is useful. .ie n .IP "$json = $json\->max_size ([$maximum_string_size])" 4 .el .IP "\f(CW$json\fR = \f(CW$json\fR\->max_size ([$maximum_string_size])" 4 .IX Item "$json = $json->max_size ([$maximum_string_size])" .PD 0 .ie n .IP "$max_size = $json\->get_max_size" 4 .el .IP "\f(CW$max_size\fR = \f(CW$json\fR\->get_max_size" 4 .IX Item "$max_size = $json->get_max_size" .PD Set the maximum length a \s-1JSON\s0 text may have (in bytes) where decoding is being attempted. The default is \f(CW0\fR, meaning no limit. When \f(CW\*(C`decode\*(C'\fR is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on \f(CW\*(C`encode\*(C'\fR (yet). .Sp If no argument is given, the limit check will be deactivated (same as when \&\f(CW0\fR is specified). .Sp See \s-1SECURITY CONSIDERATIONS,\s0 below, for more info on why this is useful. .ie n .IP "$json_text = $json\->encode ($perl_scalar)" 4 .el .IP "\f(CW$json_text\fR = \f(CW$json\fR\->encode ($perl_scalar)" 4 .IX Item "$json_text = $json->encode ($perl_scalar)" Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its \s-1JSON\s0 representation. Simple scalars will be converted into \s-1JSON\s0 string or number sequences, while references to arrays become \s-1JSON\s0 arrays and references to hashes become \s-1JSON\s0 objects. Undefined Perl values (e.g. \f(CW\*(C`undef\*(C'\fR) become \s-1JSON \s0\f(CW\*(C`null\*(C'\fR values. Neither \f(CW\*(C`true\*(C'\fR nor \f(CW\*(C`false\*(C'\fR values will be generated. .ie n .IP "$perl_scalar = $json\->decode ($json_text)" 4 .el .IP "\f(CW$perl_scalar\fR = \f(CW$json\fR\->decode ($json_text)" 4 .IX Item "$perl_scalar = $json->decode ($json_text)" The opposite of \f(CW\*(C`encode\*(C'\fR: expects a \s-1JSON\s0 text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error. .Sp \&\s-1JSON\s0 numbers and strings become simple Perl scalars. \s-1JSON\s0 arrays become Perl arrayrefs and \s-1JSON\s0 objects become Perl hashrefs. \f(CW\*(C`true\*(C'\fR becomes \&\f(CW1\fR, \f(CW\*(C`false\*(C'\fR becomes \f(CW0\fR and \f(CW\*(C`null\*(C'\fR becomes \f(CW\*(C`undef\*(C'\fR. .ie n .IP "($perl_scalar, $characters) = $json\->decode_prefix ($json_text)" 4 .el .IP "($perl_scalar, \f(CW$characters\fR) = \f(CW$json\fR\->decode_prefix ($json_text)" 4 .IX Item "($perl_scalar, $characters) = $json->decode_prefix ($json_text)" This works like the \f(CW\*(C`decode\*(C'\fR method, but instead of raising an exception when there is trailing garbage after the first \s-1JSON\s0 object, it will silently stop parsing there and return the number of characters consumed so far. .Sp This is useful if your \s-1JSON\s0 texts are not delimited by an outer protocol (which is not the brightest thing to do in the first place) and you need to know where the \s-1JSON\s0 text ends. .Sp .Vb 2 \& Cpanel::JSON::XS\->new\->decode_prefix ("[1] the tail") \& => ([], 3) .Ve .ie n .IP "$json\->to_json ($perl_hash_or_arrayref)" 4 .el .IP "\f(CW$json\fR\->to_json ($perl_hash_or_arrayref)" 4 .IX Item "$json->to_json ($perl_hash_or_arrayref)" Deprecated method for perl 5.8 and newer. Use encode_json instead. .ie n .IP "$json\->from_json ($utf8_encoded_json_text)" 4 .el .IP "\f(CW$json\fR\->from_json ($utf8_encoded_json_text)" 4 .IX Item "$json->from_json ($utf8_encoded_json_text)" Deprecated method for perl 5.8 and newer. Use decode_json instead. .SH "INCREMENTAL PARSING" .IX Header "INCREMENTAL PARSING" In some cases, there is the need for incremental parsing of \s-1JSON\s0 texts. While this module always has to keep both \s-1JSON\s0 text and resulting Perl data structure in memory at one time, it does allow you to parse a \&\s-1JSON\s0 stream incrementally. It does so by accumulating text until it has a full \s-1JSON\s0 object, which it then can decode. This process is similar to using \f(CW\*(C`decode_prefix\*(C'\fR to see if a full \s-1JSON\s0 object is available, but is much more efficient (and can be implemented with a minimum of method calls). .PP Cpanel::JSON::XS will only attempt to parse the \s-1JSON\s0 text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won't stop as early as the full parser, for example, it doesn't detect mismatched parentheses. The only thing it guarantees is that it starts decoding as soon as a syntactically valid \s-1JSON\s0 text has been seen. This means you need to set resource limits (e.g. \f(CW\*(C`max_size\*(C'\fR) to ensure the parser will stop parsing in the presence if syntax errors. .PP The following methods implement this incremental parser. .ie n .IP "[void, scalar or list context] = $json\->incr_parse ([$string])" 4 .el .IP "[void, scalar or list context] = \f(CW$json\fR\->incr_parse ([$string])" 4 .IX Item "[void, scalar or list context] = $json->incr_parse ([$string])" This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional). .Sp If \f(CW$string\fR is given, then this string is appended to the already existing \s-1JSON\s0 fragment stored in the \f(CW$json\fR object. .Sp After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want. .Sp If the method is called in scalar context, then it will try to extract exactly \fIone\fR \s-1JSON\s0 object. If that is successful, it will return this object, otherwise it will return \f(CW\*(C`undef\*(C'\fR. If there is a parse error, this method will croak just as \f(CW\*(C`decode\*(C'\fR would do (one can then use \&\f(CW\*(C`incr_skip\*(C'\fR to skip the erroneous part). This is the most common way of using the method. .Sp And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators between the \s-1JSON\s0 objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed \s-1JSON\s0 texts will be lost. .Sp Example: Parse some \s-1JSON\s0 arrays/objects in a given string and return them. .Sp .Vb 1 \& my @objs = Cpanel::JSON::XS\->new\->incr_parse ("[5][7][1,2]"); .Ve .ie n .IP "$lvalue_string = $json\->incr_text (>5.8 only)" 4 .el .IP "\f(CW$lvalue_string\fR = \f(CW$json\fR\->incr_text (>5.8 only)" 4 .IX Item "$lvalue_string = $json->incr_text (>5.8 only)" This method returns the currently stored \s-1JSON\s0 fragment as an lvalue, that is, you can manipulate it. This \fIonly\fR works when a preceding call to \&\f(CW\*(C`incr_parse\*(C'\fR in \fIscalar context\fR successfully returned an object, and 2. only with Perl >= 5.8 .Sp Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it \fIwill\fR fail under real world conditions). As a special exception, you can also call this method before having parsed anything. .Sp This function is useful in two cases: a) finding the trailing text after a \&\s-1JSON\s0 object or b) parsing multiple \s-1JSON\s0 objects separated by non-JSON text (such as commas). .ie n .IP "$json\->incr_skip" 4 .el .IP "\f(CW$json\fR\->incr_skip" 4 .IX Item "$json->incr_skip" This will reset the state of the incremental parser and will remove the parsed text from the input buffer so far. This is useful after \&\f(CW\*(C`incr_parse\*(C'\fR died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state. .Sp The difference to \f(CW\*(C`incr_reset\*(C'\fR is that only text until the parse error occurred is removed. .ie n .IP "$json\->incr_reset" 4 .el .IP "\f(CW$json\fR\->incr_reset" 4 .IX Item "$json->incr_reset" This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything. .Sp This is useful if you want to repeatedly parse \s-1JSON\s0 objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode. .SS "\s-1LIMITATIONS\s0" .IX Subsection "LIMITATIONS" All options that affect decoding are supported, except \&\f(CW\*(C`allow_nonref\*(C'\fR. The reason for this is that it cannot be made to work sensibly: \s-1JSON\s0 objects and arrays are self-delimited, i.e. you can concatenate them back to back and still decode them perfectly. This does not hold true for \s-1JSON\s0 numbers, however. .PP For example, is the string \f(CW1\fR a single \s-1JSON\s0 number, or is it simply the start of \f(CW12\fR? Or is \f(CW12\fR a single \s-1JSON\s0 number, or the concatenation of \f(CW1\fR and \f(CW2\fR? In neither case you can tell, and this is why Cpanel::JSON::XS takes the conservative route and disallows this case. .SS "\s-1EXAMPLES\s0" .IX Subsection "EXAMPLES" Some examples will make all this clearer. First, a simple example that works similarly to \f(CW\*(C`decode_prefix\*(C'\fR: We want to decode the \s-1JSON\s0 object at the start of a string and identify the portion after the \s-1JSON\s0 object: .PP .Vb 1 \& my $text = "[1,2,3] hello"; \& \& my $json = new Cpanel::JSON::XS; \& \& my $obj = $json\->incr_parse ($text) \& or die "expected JSON object or array at beginning of string"; \& \& my $tail = $json\->incr_text; \& # $tail now contains " hello" .Ve .PP Easy, isn't it? .PP Now for a more complicated example: Imagine a hypothetical protocol where you read some requests from a \s-1TCP\s0 stream, and each request is a \s-1JSON\s0 array, without any separation between them (in fact, it is often useful to use newlines as \*(L"separators\*(R", as these get interpreted as whitespace at the start of the \s-1JSON\s0 text, which makes it possible to test said protocol with \f(CW\*(C`telnet\*(C'\fR...). .PP Here is how you'd do it (it is trivial to write this in an event-based manner): .PP .Vb 1 \& my $json = new Cpanel::JSON::XS; \& \& # read some data from the socket \& while (sysread $socket, my $buf, 4096) { \& \& # split and decode as many requests as possible \& for my $request ($json\->incr_parse ($buf)) { \& # act on the $request \& } \& } .Ve .PP Another complicated example: Assume you have a string with \s-1JSON\s0 objects or arrays, all separated by (optional) comma characters (e.g. \f(CW\*(C`[1],[2], [3]\*(C'\fR). To parse them, we have to skip the commas between the \s-1JSON\s0 texts, and here is where the lvalue-ness of \f(CW\*(C`incr_text\*(C'\fR comes in useful: .PP .Vb 2 \& my $text = "[1],[2], [3]"; \& my $json = new Cpanel::JSON::XS; \& \& # void context, so no parsing done \& $json\->incr_parse ($text); \& \& # now extract as many objects as possible. note the \& # use of scalar context so incr_text can be called. \& while (my $obj = $json\->incr_parse) { \& # do something with $obj \& \& # now skip the optional comma \& $json\->incr_text =~ s/^ \es* , //x; \& } .Ve .PP Now lets go for a very complex example: Assume that you have a gigantic \&\s-1JSON\s0 array-of-objects, many gigabytes in size, and you want to parse it, but you cannot load it into memory fully (this has actually happened in the real world :). .PP Well, you lost, you have to implement your own \s-1JSON\s0 parser. But Cpanel::JSON::XS can still help you: You implement a (very simple) array parser and let \&\s-1JSON\s0 decode the array elements, which are all full \s-1JSON\s0 objects on their own (this wouldn't work if the array elements could be \s-1JSON\s0 numbers, for example): .PP .Vb 1 \& my $json = new Cpanel::JSON::XS; \& \& # open the monster \& open my $fh, "incr_parse ($buf); # void context, so no parsing \& \& # Exit the loop once we found and removed(!) the initial "[". \& # In essence, we are (ab\-)using the $json object as a simple scalar \& # we append data to. \& last if $json\->incr_text =~ s/^ \es* \e[ //x; \& } \& \& # now we have the skipped the initial "[", so continue \& # parsing all the elements. \& for (;;) { \& # in this loop we read data until we got a single JSON object \& for (;;) { \& if (my $obj = $json\->incr_parse) { \& # do something with $obj \& last; \& } \& \& # add more data \& sysread $fh, my $buf, 65536 \& or die "read error: $!"; \& $json\->incr_parse ($buf); # void context, so no parsing \& } \& \& # in this loop we read data until we either found and parsed the \& # separating "," between elements, or the final "]" \& for (;;) { \& # first skip whitespace \& $json\->incr_text =~ s/^\es*//; \& \& # if we find "]", we are done \& if ($json\->incr_text =~ s/^\e]//) { \& print "finished.\en"; \& exit; \& } \& \& # if we find ",", we can continue with the next element \& if ($json\->incr_text =~ s/^,//) { \& last; \& } \& \& # if we find anything else, we have a parse error! \& if (length $json\->incr_text) { \& die "parse error near ", $json\->incr_text; \& } \& \& # else add more data \& sysread $fh, my $buf, 65536 \& or die "read error: $!"; \& $json\->incr_parse ($buf); # void context, so no parsing \& } .Ve .PP This is a complex example, but most of the complexity comes from the fact that we are trying to be correct (bear with me if I am wrong, I never ran the above example :). .SH "MAPPING" .IX Header "MAPPING" This section describes how Cpanel::JSON::XS maps Perl values to \s-1JSON\s0 values and vice versa. These mappings are designed to \*(L"do the right thing\*(R" in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent). .PP For the more enlightened: note that in the following descriptions, lowercase \fIperl\fR refers to the Perl interpreter, while uppercase \fIPerl\fR refers to the abstract Perl language itself. .SS "\s-1JSON \-\s0> \s-1PERL\s0" .IX Subsection "JSON -> PERL" .IP "object" 4 .IX Item "object" A \s-1JSON\s0 object becomes a reference to a hash in Perl. No ordering of object keys is preserved (\s-1JSON\s0 does not preserve object key ordering itself). .IP "array" 4 .IX Item "array" A \s-1JSON\s0 array becomes a reference to an array in Perl. .IP "string" 4 .IX Item "string" A \s-1JSON\s0 string becomes a string scalar in Perl \- Unicode codepoints in \s-1JSON\s0 are represented by the same codepoints in the Perl string, so no manual decoding is necessary. .IP "number" 4 .IX Item "number" A \s-1JSON\s0 number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers. .Sp If the number consists of digits only, Cpanel::JSON::XS will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the \s-1JSON\s0 number will be re-encoded to a \s-1JSON\s0 string). .Sp Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the \s-1JSON\s0 number will still be re-encoded as a \s-1JSON\s0 number). .Sp Note that precision is not accuracy \- binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, Cpanel::JSON::XS only guarantees precision up to but not including the least significant bit. .IP "true, false" 4 .IX Item "true, false" These \s-1JSON\s0 atoms become \f(CW\*(C`JSON::XS::true\*(C'\fR and \f(CW\*(C`JSON::XS::false\*(C'\fR, respectively. They are overloaded to act almost exactly like the numbers \&\f(CW1\fR and \f(CW0\fR. You can check whether a scalar is a \s-1JSON\s0 boolean by using the \f(CW\*(C`Cpanel::JSON::XS::is_bool\*(C'\fR function. .IP "null" 4 .IX Item "null" A \s-1JSON\s0 null atom becomes \f(CW\*(C`undef\*(C'\fR in Perl. .ie n .IP "shell-style comments (""# \f(CItext\f(CW"")" 4 .el .IP "shell-style comments (\f(CW# \f(CItext\f(CW\fR)" 4 .IX Item "shell-style comments (# text)" As a nonstandard extension to the \s-1JSON\s0 syntax that is enabled by the \&\f(CW\*(C`relaxed\*(C'\fR setting, shell-style comments are allowed. They can start anywhere outside strings and go till the end of the line. .ie n .IP "tagged values (""(\f(CItag\f(CW)\f(CIvalue\f(CW"")." 4 .el .IP "tagged values (\f(CW(\f(CItag\f(CW)\f(CIvalue\f(CW\fR)." 4 .IX Item "tagged values ((tag)value)." Another nonstandard extension to the \s-1JSON\s0 syntax, enabled with the \&\f(CW\*(C`allow_tags\*(C'\fR setting, are tagged values. In this implementation, the \&\fItag\fR must be a perl package/class name encoded as a \s-1JSON\s0 string, and the \&\fIvalue\fR must be a \s-1JSON\s0 array encoding optional constructor arguments. .Sp See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0, below, for details. .SS "\s-1PERL \-\s0> \s-1JSON\s0" .IX Subsection "PERL -> JSON" The mapping from Perl to \s-1JSON\s0 is slightly more difficult, as Perl is a truly typeless language, so we can only guess which \s-1JSON\s0 type is meant by a Perl value. .IP "hash references" 4 .IX Item "hash references" Perl hash references become \s-1JSON\s0 objects. As there is no inherent ordering in hash keys (or \s-1JSON\s0 objects), they will usually be encoded in a pseudo-random order that can change between runs of the same program but stays generally the same within a single run of a program. Cpanel::JSON::XS can optionally sort the hash keys (determined by the \fIcanonical\fR flag), so the same datastructure will serialise to the same \s-1JSON\s0 text (given same settings and version of Cpanel::JSON::XS), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some \s-1JSON\s0 text against another for equality. .IP "array references" 4 .IX Item "array references" Perl array references become \s-1JSON\s0 arrays. .IP "other references" 4 .IX Item "other references" Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers \f(CW0\fR and \&\f(CW1\fR, which get turned into \f(CW\*(C`false\*(C'\fR and \f(CW\*(C`true\*(C'\fR atoms in \s-1JSON.\s0 You can also use \f(CW\*(C`JSON::XS::false\*(C'\fR and \f(CW\*(C`JSON::XS::true\*(C'\fR to improve readability. .Sp .Vb 1 \& encode_json [\e0, Cpanel::JSON::XS::true] # yields [false,true] .Ve .IP "Cpanel::JSON::XS::true, Cpanel::JSON::XS::false" 4 .IX Item "Cpanel::JSON::XS::true, Cpanel::JSON::XS::false" These special values become \s-1JSON\s0 true and \s-1JSON\s0 false values, respectively. You can also use \f(CW\*(C`\e1\*(C'\fR and \f(CW\*(C`\e0\*(C'\fR directly if you want. .IP "blessed objects" 4 .IX Item "blessed objects" Blessed objects are not directly representable in \s-1JSON,\s0 but \&\f(CW\*(C`Cpanel::JSON::XS\*(C'\fR allows various ways of handling objects. See \&\*(L"\s-1OBJECT SERIALISATION\*(R"\s0, below, for details. .Sp See the \f(CW\*(C`allow_blessed\*(C'\fR and \f(CW\*(C`convert_blessed\*(C'\fR methods on various options on how to deal with this: basically, you can choose between throwing an exception, encoding the reference as if it weren't blessed, or provide your own serialiser method. .IP "simple scalars" 4 .IX Item "simple scalars" Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: Cpanel::JSON::XS will encode undefined scalars as \&\s-1JSON \s0\f(CW\*(C`null\*(C'\fR values, scalars that have last been used in a string context before encoding as \s-1JSON\s0 strings, and anything else as number value: .Sp .Vb 4 \& # dump as number \& encode_json [2] # yields [2] \& encode_json [\-3.0e17] # yields [\-3e+17] \& my $value = 5; encode_json [$value] # yields [5] \& \& # used as string, so dump as string \& print $value; \& encode_json [$value] # yields ["5"] \& \& # undef becomes null \& encode_json [undef] # yields [null] .Ve .Sp You can force the type to be a \s-1JSON\s0 string by stringifying it: .Sp .Vb 4 \& my $x = 3.1; # some variable containing a number \& "$x"; # stringified \& $x .= ""; # another, more awkward way to stringify \& print $x; # perl does it for you, too, quite often .Ve .Sp You can force the type to be a \s-1JSON\s0 number by numifying it: .Sp .Vb 3 \& my $x = "3"; # some variable containing a string \& $x += 0; # numify it, ensuring it will be dumped as a number \& $x *= 1; # same thing, the choice is yours. .Ve .Sp You can not currently force the type in other, less obscure, ways. Tell me if you need this capability (but don't forget to explain why it's needed :). .Sp Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN's \- these cannot be represented in \s-1JSON,\s0 and it is an error to pass those in. .SS "\s-1OBJECT SERIALISATION\s0" .IX Subsection "OBJECT SERIALISATION" As \s-1JSON\s0 cannot directly represent Perl objects, you have to choose between a pure \s-1JSON\s0 representation (without the ability to deserialise the object automatically again), and a nonstandard extension to the \s-1JSON\s0 syntax, tagged values. .PP \fI\s-1SERIALISATION\s0\fR .IX Subsection "SERIALISATION" .PP What happens when \f(CW\*(C`JSON::XS\*(C'\fR encounters a Perl object depends on the \&\f(CW\*(C`allow_blessed\*(C'\fR, \f(CW\*(C`convert_blessed\*(C'\fR and \f(CW\*(C`allow_tags\*(C'\fR settings, which are used in this order: .ie n .IP "1. ""allow_tags"" is enabled and the object has a ""FREEZE"" method." 4 .el .IP "1. \f(CWallow_tags\fR is enabled and the object has a \f(CWFREEZE\fR method." 4 .IX Item "1. allow_tags is enabled and the object has a FREEZE method." In this case, \f(CW\*(C`JSON::XS\*(C'\fR uses the Types::Serialiser object serialisation protocol to create a tagged \s-1JSON\s0 value, using a nonstandard extension to the \s-1JSON\s0 syntax. .Sp This works by invoking the \f(CW\*(C`FREEZE\*(C'\fR method on the object, with the first argument being the object to serialise, and the second argument being the constant string \f(CW\*(C`JSON\*(C'\fR to distinguish it from other serialisers. .Sp The \f(CW\*(C`FREEZE\*(C'\fR method can return any number of values (i.e. zero or more). These values and the paclkage/classname of the object will then be encoded as a tagged \s-1JSON\s0 value in the following format: .Sp .Vb 1 \& ("classname")[FREEZE return values...] .Ve .Sp e.g.: .Sp .Vb 3 \& ("URI")["http://www.google.com/"] \& ("MyDate")[2013,10,29] \& ("ImageData::JPEG")["Z3...VlCg=="] .Ve .Sp For example, the hypothetical \f(CW\*(C`My::Object\*(C'\fR \f(CW\*(C`FREEZE\*(C'\fR method might use the objects \f(CW\*(C`type\*(C'\fR and \f(CW\*(C`id\*(C'\fR members to encode the object: .Sp .Vb 2 \& sub My::Object::FREEZE { \& my ($self, $serialiser) = @_; \& \& ($self\->{type}, $self\->{id}) \& } .Ve .ie n .IP "2. ""convert_blessed"" is enabled and the object has a ""TO_JSON"" method." 4 .el .IP "2. \f(CWconvert_blessed\fR is enabled and the object has a \f(CWTO_JSON\fR method." 4 .IX Item "2. convert_blessed is enabled and the object has a TO_JSON method." In this case, the \f(CW\*(C`TO_JSON\*(C'\fR method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into \&\s-1JSON.\s0 This scalar replaces the object in the \s-1JSON\s0 text. .Sp For example, the following \f(CW\*(C`TO_JSON\*(C'\fR method will convert all \s-1URI\s0 objects to \s-1JSON\s0 strings when serialised. The fatc that these values originally were \s-1URI\s0 objects is lost. .Sp .Vb 4 \& sub URI::TO_JSON { \& my ($uri) = @_; \& $uri\->as_string \& } .Ve .ie n .IP "3. ""allow_blessed"" is enabled." 4 .el .IP "3. \f(CWallow_blessed\fR is enabled." 4 .IX Item "3. allow_blessed is enabled." The object will be serialised as a \s-1JSON\s0 null value. .IP "4. none of the above" 4 .IX Item "4. none of the above" If none of the settings are enabled or the respective methods are missing, \&\f(CW\*(C`JSON::XS\*(C'\fR throws an exception. .PP \fI\s-1DESERIALISATION\s0\fR .IX Subsection "DESERIALISATION" .PP For deserialisation there are only two cases to consider: either nonstandard tagging was used, in which case \f(CW\*(C`allow_tags\*(C'\fR decides, or objects cannot be automatically be deserialised, in which case you can use postprocessing or the \f(CW\*(C`filter_json_object\*(C'\fR or \&\f(CW\*(C`filter_json_single_key_object\*(C'\fR callbacks to get some real objects our of your \s-1JSON.\s0 .PP This section only considers the tagged value case: I a tagged \s-1JSON\s0 object is encountered during decoding and \f(CW\*(C`allow_tags\*(C'\fR is disabled, a parse error will result (as if tagged values were not part of the grammar). .PP If \f(CW\*(C`allow_tags\*(C'\fR is enabled, \f(CW\*(C`JSON::XS\*(C'\fR will look up the \f(CW\*(C`THAW\*(C'\fR method of the package/classname used during serialisation (it will not attempt to load the package as a Perl module). If there is no such method, the decoding will fail with an error. .PP Otherwise, the \f(CW\*(C`THAW\*(C'\fR method is invoked with the classname as first argument, the constant string \f(CW\*(C`JSON\*(C'\fR as second argument, and all the values from the \s-1JSON\s0 array (the values originally returned by the \&\f(CW\*(C`FREEZE\*(C'\fR method) as remaining arguments. .PP The method must then return the object. While technically you can return any Perl scalar, you might have to enable the \f(CW\*(C`enable_nonref\*(C'\fR setting to make that work in all cases, so better return an actual blessed reference. .PP As an example, let's implement a \f(CW\*(C`THAW\*(C'\fR function that regenerates the \&\f(CW\*(C`My::Object\*(C'\fR from the \f(CW\*(C`FREEZE\*(C'\fR example earlier: .PP .Vb 2 \& sub My::Object::THAW { \& my ($class, $serialiser, $type, $id) = @_; \& \& $class\->new (type => $type, id => $id) \& } .Ve .SH "ENCODING/CODESET FLAG NOTES" .IX Header "ENCODING/CODESET FLAG NOTES" The interested reader might have seen a number of flags that signify encodings or codesets \- \f(CW\*(C`utf8\*(C'\fR, \f(CW\*(C`latin1\*(C'\fR, \f(CW\*(C`binary\*(C'\fR and \&\f(CW\*(C`ascii\*(C'\fR. There seems to be some confusion on what these do, so here is a short comparison: .PP \&\f(CW\*(C`utf8\*(C'\fR controls whether the \s-1JSON\s0 text created by \f(CW\*(C`encode\*(C'\fR (and expected by \f(CW\*(C`decode\*(C'\fR) is \s-1UTF\-8\s0 encoded or not, while \f(CW\*(C`latin1\*(C'\fR and \f(CW\*(C`ascii\*(C'\fR only control whether \f(CW\*(C`encode\*(C'\fR escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others. .PP Care has been taken to make all flags symmetrical with respect to \&\f(CW\*(C`encode\*(C'\fR and \f(CW\*(C`decode\*(C'\fR, that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used \&\- in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere. .PP Below comes a verbose discussion of these flags. Note that a \*(L"codeset\*(R" is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and \fIencodes\fR them, in our case into octets. Unicode is (among other things) a codeset, \s-1UTF\-8\s0 is an encoding, and \s-1ISO\-8859\-1 \s0(= latin 1) and \s-1ASCII\s0 are both codesets \fIand\fR encodings at the same time, which can be confusing. .ie n .IP """utf8"" flag disabled" 4 .el .IP "\f(CWutf8\fR flag disabled" 4 .IX Item "utf8 flag disabled" When \f(CW\*(C`utf8\*(C'\fR is disabled (the default), then \f(CW\*(C`encode\*(C'\fR/\f(CW\*(C`decode\*(C'\fR generate and expect Unicode strings, that is, characters with high ordinal Unicode values (> 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except \&\*(L"(re\-)interpreting\*(R" them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff). .Sp This is useful when you want to do the encoding yourself (e.g. when you want to have \s-1UTF\-16\s0 encoded \s-1JSON\s0 texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to \s-1UTF\-8\s0 you certainly do \s-1NOT\s0 want to \s-1UTF\-8\s0 encode your data first and have Perl encode it another time). .ie n .IP """utf8"" flag enabled" 4 .el .IP "\f(CWutf8\fR flag enabled" 4 .IX Item "utf8 flag enabled" If the \f(CW\*(C`utf8\*(C'\fR\-flag is enabled, \f(CW\*(C`encode\*(C'\fR/\f(CW\*(C`decode\*(C'\fR will encode all characters using the corresponding \s-1UTF\-8\s0 multi-byte sequence, and will expect your input strings to be encoded as \s-1UTF\-8,\s0 that is, no \*(L"character\*(R" of the input string must have any value > 255, as \s-1UTF\-8\s0 does not allow that. .Sp The \f(CW\*(C`utf8\*(C'\fR flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get an \s-1UTF\-8\s0 encoded octet/binary string in Perl. .ie n .IP """latin1"", ""binary"" or ""ascii"" flags enabled" 4 .el .IP "\f(CWlatin1\fR, \f(CWbinary\fR or \f(CWascii\fR flags enabled" 4 .IX Item "latin1, binary or ascii flags enabled" With \f(CW\*(C`latin1\*(C'\fR (or \f(CW\*(C`ascii\*(C'\fR) enabled, \f(CW\*(C`encode\*(C'\fR will escape characters with ordinal values > 255 (> 127 with \f(CW\*(C`ascii\*(C'\fR) and encode the remaining characters as specified by the \f(CW\*(C`utf8\*(C'\fR flag. With \f(CW\*(C`binary\*(C'\fR enabled, ordinal values > 255 are illegal. .Sp If \f(CW\*(C`utf8\*(C'\fR is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values < 256 is the same thing as a \&\s-1ISO\-8859\-1\s0 string, and a Unicode string with all character values < 128 is the same thing as an \s-1ASCII\s0 string in Perl). .Sp If \f(CW\*(C`utf8\*(C'\fR is enabled, you still get a correct UTF\-8\-encoded string, regardless of these flags, just some more characters will be escaped using \&\f(CW\*(C`\euXXXX\*(C'\fR then before. .Sp Note that \s-1ISO\-8859\-1\-\s0\fIencoded\fR strings are not compatible with \s-1UTF\-8\s0 encoding, while ASCII-encoded strings are. That is because the \s-1ISO\-8859\-1\s0 encoding is \s-1NOT\s0 a subset of \s-1UTF\-8 \s0(despite the \s-1ISO\-8859\-1 \s0\fIcodeset\fR being a subset of Unicode), while \s-1ASCII\s0 is. .Sp Surprisingly, \f(CW\*(C`decode\*(C'\fR will ignore these flags and so treat all input values as governed by the \f(CW\*(C`utf8\*(C'\fR flag. If it is disabled, this allows you to decode \s-1ISO\-8859\-1\-\s0 and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode \s-1UTF\-8\s0 encoded strings. .Sp So neither \f(CW\*(C`latin1\*(C'\fR, \f(CW\*(C`binary\*(C'\fR nor \f(CW\*(C`ascii\*(C'\fR are incompatible with the \&\f(CW\*(C`utf8\*(C'\fR flag \- they only govern when the \s-1JSON\s0 output engine escapes a character or not. .Sp The main use for \f(CW\*(C`latin1\*(C'\fR or \f(CW\*(C`binary\*(C'\fR is to relatively efficiently store binary data as \s-1JSON,\s0 at the expense of breaking compatibility with most \s-1JSON\s0 decoders. .Sp The main use for \f(CW\*(C`ascii\*(C'\fR is to force the output to not contain characters with values > 127, which means you can interpret the resulting string as \s-1UTF\-8, ISO\-8859\-1, ASCII, KOI8\-R\s0 or most about any character set and 8\-bit\-encoding, and still get the same data structure back. This is useful when your channel for \s-1JSON\s0 transfer is not 8\-bit clean or the encoding might be mangled in between (e.g. in mail), and works because \s-1ASCII\s0 is a proper subset of most 8\-bit and multibyte encodings in use in the world. .SS "\s-1JSON\s0 and ECMAscript" .IX Subsection "JSON and ECMAscript" \&\s-1JSON\s0 syntax is based on how literals are represented in javascript (the not-standardised predecessor of ECMAscript) which is presumably why it is called \*(L"JavaScript Object Notation\*(R". .PP However, \s-1JSON\s0 is not a subset (and also not a superset of course) of ECMAscript (the standard) or javascript (whatever browsers actually implement). .PP If you want to use javascript's \f(CW\*(C`eval\*(C'\fR function to \*(L"parse\*(R" \s-1JSON,\s0 you might run into parse errors for valid \s-1JSON\s0 texts, or the resulting data structure might not be queryable: .PP One of the problems is that U+2028 and U+2029 are valid characters inside \&\s-1JSON\s0 strings, but are not allowed in ECMAscript string literals, so the following Perl fragment will not output something that can be guaranteed to be parsable by javascript's \f(CW\*(C`eval\*(C'\fR: .PP .Vb 1 \& use Cpanel::JSON::XS; \& \& print encode_json [chr 0x2028]; .Ve .PP The right fix for this is to use a proper \s-1JSON\s0 parser in your javascript programs, and not rely on \f(CW\*(C`eval\*(C'\fR (see for example Douglas Crockford's \&\fIjson2.js\fR parser). .PP If this is not an option, you can, as a stop-gap measure, simply encode to ASCII-only \s-1JSON:\s0 .PP .Vb 1 \& use Cpanel::JSON::XS; \& \& print Cpanel::JSON::XS\->new\->ascii\->encode ([chr 0x2028]); .Ve .PP Note that this will enlarge the resulting \s-1JSON\s0 text quite a bit if you have many non-ASCII characters. You might be tempted to run some regexes to only escape U+2028 and U+2029, e.g.: .PP .Vb 5 \& # DO NOT USE THIS! \& my $json = Cpanel::JSON::XS\->new\->utf8\->encode ([chr 0x2028]); \& $json =~ s/\exe2\ex80\exa8/\e\eu2028/g; # escape U+2028 \& $json =~ s/\exe2\ex80\exa9/\e\eu2029/g; # escape U+2029 \& print $json; .Ve .PP Note that \fIthis is a bad idea\fR: the above only works for U+2028 and U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing javascript implementations, however, have issues with other characters as well \- using \f(CW\*(C`eval\*(C'\fR naively simply \fIwill\fR cause problems. .PP Another problem is that some javascript implementations reserve some property names for their own purposes (which probably makes them non-ECMAscript-compliant). For example, Iceweasel reserves the \&\f(CW\*(C`_\|_proto_\|_\*(C'\fR property name for its own purposes. .PP If that is a problem, you could parse try to filter the resulting \s-1JSON\s0 output for these property strings, e.g.: .PP .Vb 1 \& $json =~ s/"_\|_proto_\|_"\es*:/"_\|_proto_\|_renamed":/g; .Ve .PP This works because \f(CW\*(C`_\|_proto_\|_\*(C'\fR is not valid outside of strings, so every occurrence of \f(CW\*(C`"_\|_proto_\|_"\es*:\*(C'\fR must be a string used as property name. .PP If you know of other incompatibilities, please let me know. .SS "\s-1JSON\s0 and \s-1YAML\s0" .IX Subsection "JSON and YAML" You often hear that \s-1JSON\s0 is a subset of \s-1YAML.\s0 This is, however, a mass hysteria(*) and very far from the truth (as of the time of this writing), so let me state it clearly: \fIin general, there is no way to configure \&\s-1JSON::XS\s0 to output a data structure as valid \s-1YAML\s0\fR that works in all cases. .PP If you really must use Cpanel::JSON::XS to generate \s-1YAML,\s0 you should use this algorithm (subject to change in future versions): .PP .Vb 2 \& my $to_yaml = Cpanel::JSON::XS\->new\->utf8\->space_after (1); \& my $yaml = $to_yaml\->encode ($ref) . "\en"; .Ve .PP This will \fIusually\fR generate \s-1JSON\s0 texts that also parse as valid \&\s-1YAML.\s0 Please note that \s-1YAML\s0 has hardcoded limits on (simple) object key lengths that \s-1JSON\s0 doesn't have and also has different and incompatible unicode character escape syntax, so you should make sure that your hash keys are noticeably shorter than the 1024 \*(L"stream characters\*(R" \s-1YAML\s0 allows and that you do not have characters with codepoint values outside the Unicode \s-1BMP \s0(basic multilingual page). \s-1YAML\s0 also does not allow \f(CW\*(C`\e/\*(C'\fR sequences in strings (which Cpanel::JSON::XS does not \fIcurrently\fR generate, but other \s-1JSON\s0 generators might). .PP There might be other incompatibilities that I am not aware of (or the \s-1YAML\s0 specification has been changed yet again \- it does so quite often). In general you should not try to generate \s-1YAML\s0 with a \s-1JSON\s0 generator or vice versa, or try to parse \s-1JSON\s0 with a \s-1YAML\s0 parser or vice versa: chances are high that you will run into severe interoperability problems when you least expect it. .IP "(*)" 4 I have been pressured multiple times by Brian Ingerson (one of the authors of the \s-1YAML\s0 specification) to remove this paragraph, despite him acknowledging that the actual incompatibilities exist. As I was personally bitten by this \*(L"\s-1JSON\s0 is \s-1YAML\*(R"\s0 lie, I refused and said I will continue to educate people about these issues, so others do not run into the same problem again and again. After this, Brian called me a (quote)\fIcomplete and worthless idiot\fR(unquote). .Sp In my opinion, instead of pressuring and insulting people who actually clarify issues with \s-1YAML\s0 and the wrong statements of some of its proponents, I would kindly suggest reading the \s-1JSON\s0 spec (which is not that difficult or long) and finally make \s-1YAML\s0 compatible to it, and educating users about the changes, instead of spreading lies about the real compatibility for many \fIyears\fR and trying to silence people who point out that it isn't true. .Sp Addendum/2009: the \s-1YAML 1.2\s0 spec is still incompatible with \s-1JSON,\s0 even though the incompatibilities have been documented (and are known to Brian) for many years and the spec makes explicit claims that \s-1YAML\s0 is a superset of \s-1JSON.\s0 It would be so easy to fix, but apparently, bullying people and corrupting userdata is so much easier. .SS "\s-1SPEED\s0" .IX Subsection "SPEED" It seems that \s-1JSON::XS\s0 is surprisingly fast, as shown in the following tables. They have been generated with the help of the \f(CW\*(C`eg/bench\*(C'\fR program in the \s-1JSON::XS\s0 distribution, to make it easy to compare on your own system. .PP \&\s-1JSON::XS\s0 is with Data::MessagePack one of the fastest serializers, because \s-1JSON\s0 and \s-1JSON::XS\s0 do not support backrefs (no graph structures), only trees. Storable supports backrefs, i.e. graphs. Data::MessagePack encodes its data binary (as Storable) and supports only very simple subset of \s-1JSON.\s0 .PP First comes a comparison between various modules using a very short single-line \s-1JSON\s0 string (also available at ). .PP .Vb 3 \& {"method": "handleMessage", "params": ["user1", \& "we were just talking"], "id": null, "array":[1,11,234,\-5,1e5,1e7, \& 1, 0]} .Ve .PP It shows the number of encodes/decodes per second (\s-1JSON::XS\s0 uses the functional interface, while Cpanel::JSON::XS/2 uses the \s-1OO\s0 interface with pretty-printing and hashkey sorting enabled, Cpanel::JSON::XS/3 enables shrink. \s-1JSON::DWIW/DS\s0 uses the deserialise function, while \s-1JSON::DWIW::FJ\s0 uses the from_json method). Higher is better: .PP .Vb 11 \& module | encode | decode | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-| \& JSON::DWIW/DS | 86302.551 | 102300.098 | \& JSON::DWIW/FJ | 86302.551 | 75983.768 | \& JSON::PP | 15827.562 | 6638.658 | \& JSON::Syck | 63358.066 | 47662.545 | \& JSON::XS | 511500.488 | 511500.488 | \& JSON::XS/2 | 291271.111 | 388361.481 | \& JSON::XS/3 | 361577.931 | 361577.931 | \& Storable | 66788.280 | 265462.278 | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .PP That is, \s-1JSON::XS\s0 is almost six times faster than \s-1JSON::DWIW\s0 on encoding, about five times faster on decoding, and over thirty to seventy times faster than \s-1JSON\s0's pure perl implementation. It also compares favourably to Storable for small amounts of data. .PP Using a longer test string (roughly 18KB, generated from Yahoo! Locals search \s-1API \s0(). .PP .Vb 11 \& module | encode | decode | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-| \& JSON::DWIW/DS | 1647.927 | 2673.916 | \& JSON::DWIW/FJ | 1630.249 | 2596.128 | \& JSON::PP | 400.640 | 62.311 | \& JSON::Syck | 1481.040 | 1524.869 | \& JSON::XS | 20661.596 | 9541.183 | \& JSON::XS/2 | 10683.403 | 9416.938 | \& JSON::XS/3 | 20661.596 | 9400.054 | \& Storable | 19765.806 | 10000.725 | \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .PP Again, \s-1JSON::XS\s0 leads by far (except for Storable which non-surprisingly decodes a bit faster). .PP On large strings containing lots of high Unicode characters, some modules (such as \s-1JSON::PC\s0) seem to decode faster than \s-1JSON::XS,\s0 but the result will be broken due to missing (or wrong) Unicode handling. Others refuse to decode or encode properly, so it was impossible to prepare a fair comparison table for that case. .SH "INTEROP with JSON and JSON::XS" .IX Header "INTEROP with JSON and JSON::XS" \&\s-1JSON\-XS\-3.01\s0 broke interoperability with \s-1JSON\-2.90\s0 with booleans. See \s-1JSON\s0. .PP Cpanel::JSON::XS needs to know the \s-1JSON\s0 and \s-1JSON::XS\s0 versions to be able work with those objects, especially when encoding a booleans like \f(CW\*(C`{"is_true":true}\*(C'\fR. So you need to load these modules before. .PP true/false overloading is supported. .PP \&\s-1JSON::XS\s0 and \s-1JSON::PP\s0 representations are accepted and older \s-1JSON::XS\s0 accepts Cpanel::JSON::XS booleans. .PP I cannot think of any reason to still use \s-1JSON::XS\s0 anymore. .SH "SECURITY CONSIDERATIONS" .IX Header "SECURITY CONSIDERATIONS" When you are using \s-1JSON\s0 in a protocol, talking to untrusted potentially hostile creatures requires relatively few measures. .PP First of all, your \s-1JSON\s0 decoder should be secure, that is, should not have any buffer overflows. Obviously, this module should ensure that and I am trying hard on making that true, but you never know. .PP Second, you need to avoid resource-starving attacks. That means you should limit the size of \s-1JSON\s0 texts you accept, or make sure then when your resources run out, that's just fine (e.g. by using a separate process that can crash safely). The size of a \s-1JSON\s0 text in octets or characters is usually a good indication of the size of the resources required to decode it into a Perl structure. While \s-1JSON::XS\s0 can check the size of the \s-1JSON\s0 text, it might be too late when you already have it in memory, so you might want to check the size before you accept the string. .PP Third, \s-1JSON::XS\s0 recurses using the C stack when decoding objects and arrays. The C stack is a limited resource: for instance, on my amd64 machine with 8MB of stack size I can decode around 180k nested arrays but only 14k nested \s-1JSON\s0 objects (due to perl itself recursing deeply on croak to free the temporary). If that is exceeded, the program crashes. To be conservative, the default nesting limit is set to 512. If your process has a smaller stack, you should adjust this setting accordingly with the \&\f(CW\*(C`max_depth\*(C'\fR method. .PP Something else could bomb you, too, that I forgot to think of. In that case, you get to keep the pieces. I am always open for hints, though... .PP Also keep in mind that \s-1JSON::XS\s0 might leak contents of your Perl data structures in its error messages, so when you serialise sensitive information you might want to make sure that exceptions thrown by \s-1JSON::XS\s0 will not end up in front of untrusted eyes. .PP If you are using \s-1JSON::XS\s0 to return packets to consumption by JavaScript scripts in a browser you should have a look at to see whether you are vulnerable to some common attack vectors (which really are browser design bugs, but it is still you who will have to deal with it, as major browser developers care only for features, not about getting security right). .SH "THREADS" .IX Header "THREADS" Cpanel::JSON::XS has experimental ithreads support, unlike \s-1JSON::XS.\s0 If you encouter any bugs with thread support please report them. .SH "BUGS" .IX Header "BUGS" While the goal of the \s-1JSON::XS\s0 module is to be correct, that unfortunately does not mean it's bug-free, only that the author thinks its design is bug-free. If you keep reporting bugs they will be fixed swiftly, though. .PP Since the \s-1JSON::XS\s0 author refuses to use a public bugtracker and prefers private emails, we've setup a tracker at \s-1RT,\s0 so you might want to report any issues twice. Once in private to \s-1MLEHMANN\s0 to be fixed in \&\s-1JSON::XS\s0 for the masses and one to our the public tracker. Issues fixed by \s-1JSON::XS\s0 with a new release will also be backported to Cpanel::JSON::XS and 5.6.2, as long as Cpanel relies on 5.6.2 and \&\s-1JSON::XS\s0 as our serializer of choice. .PP .SH "LICENSE" .IX Header "LICENSE" This module is available under the same licences as perl, the Artistic license and the \s-1GPL.\s0 .SH "SEE ALSO" .IX Header "SEE ALSO" The \fIcpanel_json_xs\fR command line utility for quick experiments. .SH "AUTHOR" .IX Header "AUTHOR" .Vb 2 \& Marc Lehmann \& http://home.schmorp.de/ \& \& cPanel Inc. .Ve .SH "MAINTAINER" .IX Header "MAINTAINER" .Vb 1 \& cPanel Inc. .Ve