[ SEA-GHOST MINI SHELL]
.\" Automatically generated by Pod::Man 2.27 (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 3"
.TH XS 3 "2020-10-27" "perl v5.16.3" "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"
JSON::XS \- JSON serialising/deserialising, done correctly and fast
.PP
JSON::XS \- XXXXXXX JSON XXXXXX/XXXXXXX
(http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html)
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 1
\& use 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 = JSON::XS\->new\->ascii\->pretty\->allow_nonref;
\& $pretty_printed_unencoded = $coder\->encode ($perl_scalar);
\& $perl_scalar = $coder\->decode ($unicode_json_text);
\&
\& # Note that JSON version 2.0 and above will automatically use JSON::XS
\& # if available, at virtually no speed overhead either, so you should
\& # be able to just:
\&
\& use JSON;
\&
\& # and do the same things, except that you have a pure\-perl fallback now.
.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
See \s-1MAPPING,\s0 below, on how \s-1JSON::XS\s0 maps perl values to \s-1JSON\s0 values and
vice versa.
.SS "\s-1FEATURES\s0"
.IX Subsection "FEATURES"
.IP "\(bu" 4
correct Unicode handling
.Sp
This module knows how to handle Unicode, 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.
.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 = 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 a \s-1UTF\-8 \s0(binary) string and tries
to parse that as a \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 = JSON::XS\->new\->utf8\->decode ($json_text)
.Ve
.Sp
Except being faster.
.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."
Just ignore that flag unless you debug a Perl bug, a module written in
\&\s-1XS\s0 or want to dive into the internals of perl. Otherwise it will only
confuse you, as, despite the name, it says nothing about how your string
is encoded. You can have Unicode strings with that flag set, with that
flag clear, and you can have binary data with that flag set and that flag
clear. Other possibilities exist, too.
.Sp
If you didn't know about that flag, just the better, pretend it doesn't
exist.
.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."
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."
It's a fact. Learn to live with it.
.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 \s-1JSON::XS\s0" 4
.el .IP "\f(CW$json\fR = new \s-1JSON::XS\s0" 4
.IX Item "$json = new JSON::XS"
Creates a new \s-1JSON::XS\s0 object that can be used to de/encode \s-1JSON\s0
strings. All boolean flags described below are by default \fIdisabled\fR
(with the exception of \f(CW\*(C`allow_nonref\*(C'\fR, which defaults to \fIenabled\fR since
version \f(CW4.0\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 = 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
\& 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
\& 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\->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 handed a 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", JSON::XS\->new\->encode ($object);
.Ve
.Sp
Example, decode UTF\-32LE\-encoded \s-1JSON:\s0
.Sp
.Vb 2
\& use Encode;
\& $object = 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 = 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 any way. \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
.IP "\(bu" 4
literal \s-1ASCII TAB\s0 characters in strings
.Sp
Literal \s-1ASCII TAB\s0 characters are now allowed in strings (and treated as
\&\f(CW\*(C`\et\*(C'\fR).
.Sp
.Vb 4
\& [
\& "Hello\etWorld",
\& "Hello<TAB>World", # literal <TAB> would not normally be allowed
\& ]
.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, and can change even within the same run from 5.18
onwards).
.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
Unlike other boolean options, this opotion is enabled by default beginning
with version \f(CW4.0\fR. See \*(L"\s-1SECURITY CONSIDERATIONS\*(R"\s0 for the gory details.
.Sp
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 without enabled \f(CW\*(C`allow_nonref\*(C'\fR,
resulting in an error:
.Sp
.Vb 2
\& JSON::XS\->new\->allow_nonref (0)\->encode ("Hello, World!")
\& => hash\- or arrayref expected...
.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<allow_nonref>.
.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
See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0 for details.
.Sp
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 that it cannot convert
otherwise. Instead, a \s-1JSON \s0\f(CW\*(C`null\*(C'\fR value is encoded instead of the object.
.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 that it cannot convert
otherwise.
.Sp
This setting has no effect on \f(CW\*(C`decode\*(C'\fR.
.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
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`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.
.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
If \f(CW$enable\fR is false (the default), then \f(CW\*(C`encode\*(C'\fR will not consider
this type of conversion.
.Sp
This setting has no effect on \f(CW\*(C`decode\*(C'\fR.
.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\->boolean_values ([$false, $true])" 4
.el .IP "\f(CW$json\fR\->boolean_values ([$false, \f(CW$true\fR])" 4
.IX Item "$json->boolean_values ([$false, $true])"
.PD 0
.ie n .IP "($false, $true) = $json\->get_boolean_values" 4
.el .IP "($false, \f(CW$true\fR) = \f(CW$json\fR\->get_boolean_values" 4
.IX Item "($false, $true) = $json->get_boolean_values"
.PD
By default, \s-1JSON\s0 booleans will be decoded as overloaded
\&\f(CW$Types::Serialiser::false\fR and \f(CW$Types::Serialiser::true\fR objects.
.Sp
With this method you can specify your own boolean values for decoding \-
on decode, \s-1JSON \s0\f(CW\*(C`false\*(C'\fR will be decoded as a copy of \f(CW$false\fR, and \s-1JSON
\&\s0\f(CW\*(C`true\*(C'\fR will be decoded as \f(CW$true\fR (\*(L"copy\*(R" here is the same thing as
assigning a value to another variable, i.e. \f(CW\*(C`$copy = $false\*(C'\fR).
.Sp
Calling this method without any arguments will reset the booleans
to their default values.
.Sp
\&\f(CW\*(C`get_boolean_values\*(C'\fR will return both \f(CW$false\fR and \f(CW$true\fR values, or
the empty list when they are set to the default.
.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 reference returns a single scalar
(which need not be a reference), this value (or rather a copy of it) 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 = 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_\|_" => <id> }\*(C'\fR
into the corresponding \f(CW$WIDGET{<id>}\fR object:
.Sp
.Vb 7
\& # return whatever is in $WIDGET{5}:
\& 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 value or data structure to its \s-1JSON\s0
representation. Croaks on error.
.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.
.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
and you need to know where the \s-1JSON\s0 text ends.
.Sp
.Vb 2
\& JSON::XS\->new\->decode_prefix ("[1] the tail")
\& => ([1], 3)
.Ve
.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
\&\s-1JSON::XS\s0 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 (other than
whitespace) 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 = JSON::XS\->new\->incr_parse ("[5][7][1,2]");
.Ve
.ie n .IP "$lvalue_string = $json\->incr_text" 4
.el .IP "\f(CW$lvalue_string\fR = \f(CW$json\fR\->incr_text" 4
.IX Item "$lvalue_string = $json->incr_text"
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. 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
That means you can only use this function to look at or manipulate text
before or after complete \s-1JSON\s0 objects, not while the parser is in the
middle of parsing a \s-1JSON\s0 object.
.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"
The incremental parser is a non-exact parser: it works by gathering as
much text as possible that \fIcould\fR be a valid \s-1JSON\s0 text, followed by
trying to decode it.
.PP
That means it sometimes needs to read more data than strictly necessary to
diagnose an invalid \s-1JSON\s0 text. For example, after parsing the following
fragment, the parser \fIcould\fR stop with an error, as this fragment
\&\fIcannot\fR be the beginning of a valid \s-1JSON\s0 text:
.PP
.Vb 1
\& [,
.Ve
.PP
In reality, hopwever, the parser might continue to read data until a
length limit is exceeded or it finds a closing bracket.
.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 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 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 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 \s-1JSON::XS\s0
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 JSON::XS;
\&
\& # open the monster
\& open my $fh, "<bigfile.json"
\& or die "bigfile: $!";
\&
\& # first parse the initial "["
\& for (;;) {
\& sysread $fh, my $buf, 65536
\& or die "read error: $!";
\& $json\->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 \s-1JSON::XS\s0 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, \s-1JSON::XS\s0 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, \s-1JSON::XS\s0 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`Types::Serialiser::true\*(C'\fR and
\&\f(CW\*(C`Types::Serialiser::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`Types::Serialiser::is_bool\*(C'\fR
function (after \f(CW\*(C`use Types::Serialier\*(C'\fR, of course).
.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. \s-1JSON::XS\s0 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
\&\s-1JSON::XS\s0), 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
.Sp
Since \f(CW\*(C`JSON::XS\*(C'\fR uses the boolean model from Types::Serialiser, you
can also \f(CW\*(C`use Types::Serialiser\*(C'\fR and then use \f(CW\*(C`Types::Serialiser::false\*(C'\fR
and \f(CW\*(C`Types::Serialiser::true\*(C'\fR to improve readability.
.Sp
.Vb 2
\& use Types::Serialiser;
\& encode_json [\e0, Types::Serialiser::true] # yields [false,true]
.Ve
.IP "Types::Serialiser::true, Types::Serialiser::false" 4
.IX Item "Types::Serialiser::true, Types::Serialiser::false"
These special values from the Types::Serialiser module 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`JSON::XS\*(C'\fR
allows various ways of handling objects. See \*(L"\s-1OBJECT SERIALISATION\*(R"\s0,
below, for details.
.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: \s-1JSON::XS\s0 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 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 a \s-1UTF\-8\s0 encoded
octet/binary string in Perl.
.ie n .IP """latin1"" or ""ascii"" flags enabled" 4
.el .IP "\f(CWlatin1\fR or \f(CWascii\fR flags enabled" 4
.IX Item "latin1 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.
.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 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 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 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 JSON::XS;
\&
\& print 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 = 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 \s-1JSON::XS\s0 to generate \s-1YAML,\s0 you should use this
algorithm (subject to change in future versions):
.PP
.Vb 2
\& my $to_yaml = 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 \s-1JSON::XS\s0 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
First comes a comparison between various modules using
a very short single-line \s-1JSON\s0 string (also available at
<http://dist.schmorp.de/misc/json/short.json>).
.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 \s-1JSON::XS/2\s0 uses the \s-1OO\s0 interface
with pretty-printing and hashkey sorting enabled, \s-1JSON::XS/3\s0 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(<http://dist.schmorp.de/misc/json/long.json>).
.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 "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
<http://blog.archive.jpsykes.com/47/practical\-csrf\-and\-json\-security/> 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).
.ie n .SS """\s-1OLD"" VS. ""NEW"" JSON \s0(\s-1RFC4627 VS. RFC7159\s0)"
.el .SS "``\s-1OLD'' VS. ``NEW'' JSON \s0(\s-1RFC4627 VS. RFC7159\s0)"
.IX Subsection "OLD VS. NEW JSON (RFC4627 VS. RFC7159)"
\&\s-1JSON\s0 originally required \s-1JSON\s0 texts to represent an array or object \-
scalar values were explicitly not allowed. This has changed, and versions
of \s-1JSON::XS\s0 beginning with \f(CW4.0\fR reflect this by allowing scalar values
by default.
.PP
One reason why one might not want this is that this removes a fundamental
property of \s-1JSON\s0 texts, namely that they are self-delimited and
self-contained, or in other words, you could take any number of \*(L"old\*(R"
\&\s-1JSON\s0 texts and paste them together, and the result would be unambiguously
parseable:
.PP
.Vb 1
\& [1,3]{"k":5}[][null] # four JSON texts, without doubt
.Ve
.PP
By allowing scalars, this property is lost: in the following example, is
this one \s-1JSON\s0 text (the number 12) or two \s-1JSON\s0 texts (the numbers 1 and
2):
.PP
.Vb 1
\& 12 # could be 12, or 1 and 2
.Ve
.PP
Another lost property of \*(L"old\*(R" \s-1JSON\s0 is that no lookahead is required to
know the end of a \s-1JSON\s0 text, i.e. the \s-1JSON\s0 text definitely ended at the
last \f(CW\*(C`]\*(C'\fR or \f(CW\*(C`}\*(C'\fR character, there was no need to read extra characters.
.PP
For example, a viable network protocol with \*(L"old\*(R" \s-1JSON\s0 was to simply
exchange \s-1JSON\s0 texts without delimiter. For \*(L"new\*(R" \s-1JSON,\s0 you have to use a
suitable delimiter (such as a newline) after every \s-1JSON\s0 text or ensure you
never encode/decode scalar values.
.PP
Most protocols do work by only transferring arrays or objects, and the
easiest way to avoid problems with the \*(L"new\*(R" \s-1JSON\s0 definition is to
explicitly disallow scalar values in your encoder and decoder:
.PP
.Vb 1
\& $json_coder = JSON::XS\->new\->allow_nonref (0)
.Ve
.PP
This is a somewhat unhappy situation, and the blame can fully be put on
\&\s-1JSON\s0's inmventor, Douglas Crockford, who unilaterally changed the format
in 2006 without consulting the \s-1IETF,\s0 forcing the \s-1IETF\s0 to either fork the
format or go with it (as I was told, the \s-1IETF\s0 wasn't amused).
.SH "RELATIONSHIP WITH I\-JSON"
.IX Header "RELATIONSHIP WITH I-JSON"
\&\s-1JSON\s0 is a somewhat sloppily-defined format \- it carries around obvious
Javascript baggage, such as not really defining number range, probably
because Javascript only has one type of numbers: \s-1IEEE 64\s0 bit floats
(\*(L"binary64\*(R").
.PP
For this reaosn, \s-1RFC7493\s0 defines \*(L"Internet \s-1JSON\*(R",\s0 which is a restricted
subset of \s-1JSON\s0 that is supposedly more interoperable on the internet.
.PP
While \f(CW\*(C`JSON::XS\*(C'\fR does not offer specific support for I\-JSON, it of course
accepts valid I\-JSON and by default implements some of the limitations
of I\-JSON, such as parsing numbers as perl numbers, which are usually a
superset of binary64 numbers.
.PP
To generate I\-JSON, follow these rules:
.IP "\(bu" 4
always generate \s-1UTF\-8\s0
.Sp
I\-JSON must be encoded in \s-1UTF\-8,\s0 the default for \f(CW\*(C`encode_json\*(C'\fR.
.IP "\(bu" 4
numbers should be within \s-1IEEE 754\s0 binary64 range
.Sp
Basically all existing perl installations use binary64 to represent
floating point numbers, so all you need to do is to avoid large integers.
.IP "\(bu" 4
objects must not have duplicate keys
.Sp
This is trivially done, as \f(CW\*(C`JSON::XS\*(C'\fR does not allow duplicate keys.
.IP "\(bu" 4
do not generate scalar \s-1JSON\s0 texts, use \f(CW\*(C`\->allow_nonref (0)\*(C'\fR
.Sp
I\-JSON strongly requests you to only encode arrays and objects into \s-1JSON.\s0
.IP "\(bu" 4
times should be strings in \s-1ISO 8601\s0 format
.Sp
There are a myriad of modules on \s-1CPAN\s0 dealing with \s-1ISO 8601 \-\s0 search for
\&\f(CW\*(C`ISO8601\*(C'\fR on \s-1CPAN\s0 and use one.
.IP "\(bu" 4
encode binary data as base64
.Sp
While it's tempting to just dump binary data as a string (and let
\&\f(CW\*(C`JSON::XS\*(C'\fR do the escaping), for I\-JSON, it's \fIrecommended\fR to encode
binary data as base64.
.PP
There are some other considerations \- read \s-1RFC7493\s0 for the details if
interested.
.SH "INTEROPERABILITY WITH OTHER MODULES"
.IX Header "INTEROPERABILITY WITH OTHER MODULES"
\&\f(CW\*(C`JSON::XS\*(C'\fR uses the Types::Serialiser module to provide boolean
constants. That means that the \s-1JSON\s0 true and false values will be
comaptible to true and false values of other modules that do the same,
such as \s-1JSON::PP\s0 and \s-1CBOR::XS\s0.
.SH "INTEROPERABILITY WITH OTHER JSON DECODERS"
.IX Header "INTEROPERABILITY WITH OTHER JSON DECODERS"
As long as you only serialise data that can be directly expressed in \s-1JSON,
\&\s0\f(CW\*(C`JSON::XS\*(C'\fR is incapable of generating invalid \s-1JSON\s0 output (modulo bugs,
but \f(CW\*(C`JSON::XS\*(C'\fR has found more bugs in the official \s-1JSON\s0 testsuite (1)
than the official \s-1JSON\s0 testsuite has found in \f(CW\*(C`JSON::XS\*(C'\fR (0)).
.PP
When you have trouble decoding \s-1JSON\s0 generated by this module using other
decoders, then it is very likely that you have an encoding mismatch or the
other decoder is broken.
.PP
When decoding, \f(CW\*(C`JSON::XS\*(C'\fR is strict by default and will likely catch all
errors. There are currently two settings that change this: \f(CW\*(C`relaxed\*(C'\fR
makes \f(CW\*(C`JSON::XS\*(C'\fR accept (but not generate) some non-standard extensions,
and \f(CW\*(C`allow_tags\*(C'\fR will allow you to encode and decode Perl objects, at the
cost of not outputting valid \s-1JSON\s0 anymore.
.SS "\s-1TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS\s0"
.IX Subsection "TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS"
When you use \f(CW\*(C`allow_tags\*(C'\fR to use the extended (and also nonstandard and
invalid) \s-1JSON\s0 syntax for serialised objects, and you still want to decode
the generated When you want to serialise objects, you can run a regex
to replace the tagged syntax by standard \s-1JSON\s0 arrays (it only works for
\&\*(L"normal\*(R" package names without comma, newlines or single colons). First,
the readable Perl version:
.PP
.Vb 2
\& # if your FREEZE methods return no values, you need this replace first:
\& $json =~ s/\e( \es* (" (?: [^\e\e":,]+|\e\e.|::)* ") \es* \e) \es* \e[\es*\e]/[$1]/gx;
\&
\& # this works for non\-empty constructor arg lists:
\& $json =~ s/\e( \es* (" (?: [^\e\e":,]+|\e\e.|::)* ") \es* \e) \es* \e[/[$1,/gx;
.Ve
.PP
And here is a less readable version that is easy to adapt to other
languages:
.PP
.Vb 1
\& $json =~ s/\e(\es*("([^\e\e":,]+|\e\e.|::)*")\es*\e)\es*\e[/[$1,/g;
.Ve
.PP
Here is an ECMAScript version (same regex):
.PP
.Vb 1
\& json = json.replace (/\e(\es*("([^\e\e":,]+|\e\e.|::)*")\es*\e)\es*\e[/g, "[$1,");
.Ve
.PP
Since this syntax converts to standard \s-1JSON\s0 arrays, it might be hard to
distinguish serialised objects from normal arrays. You can prepend a
\&\*(L"magic number\*(R" as first array element to reduce chances of a collision:
.PP
.Vb 1
\& $json =~ s/\e(\es*("([^\e\e":,]+|\e\e.|::)*")\es*\e)\es*\e[/["XU1peReLzT4ggEllLanBYq4G9VzliwKF",$1,/g;
.Ve
.PP
And after decoding the \s-1JSON\s0 text, you could walk the data
structure looking for arrays with a first element of
\&\f(CW\*(C`XU1peReLzT4ggEllLanBYq4G9VzliwKF\*(C'\fR.
.PP
The same approach can be used to create the tagged format with another
encoder. First, you create an array with the magic string as first member,
the classname as second, and constructor arguments last, encode it as part
of your \s-1JSON\s0 structure, and then:
.PP
.Vb 1
\& $json =~ s/\e[\es*"XU1peReLzT4ggEllLanBYq4G9VzliwKF"\es*,\es*("([^\e\e":,]+|\e\e.|::)*")\es*,/($1)[/g;
.Ve
.PP
Again, this has some limitations \- the magic string must not be encoded
with character escapes, and the constructor arguments must be non-empty.
.SH "(I\-)THREADS"
.IX Header "(I-)THREADS"
This module is \fInot\fR guaranteed to be ithread (or \s-1MULTIPLICITY\-\s0) safe
and there are no plans to change this. Note that perl's builtin so-called
threads/ithreads are officially deprecated and should not be used.
.SH "THE PERILS OF SETLOCALE"
.IX Header "THE PERILS OF SETLOCALE"
Sometimes people avoid the Perl locale support and directly call the
system's setlocale function with \f(CW\*(C`LC_ALL\*(C'\fR.
.PP
This breaks both perl and modules such as \s-1JSON::XS,\s0 as stringification of
numbers no longer works correctly (e.g. \f(CW\*(C`$x = 0.1; print "$x"+1\*(C'\fR might
print \f(CW1\fR, and \s-1JSON::XS\s0 might output illegal \s-1JSON\s0 as \s-1JSON::XS\s0 relies on
perl to stringify numbers).
.PP
The solution is simple: don't call \f(CW\*(C`setlocale\*(C'\fR, or use it for only those
categories you need, such as \f(CW\*(C`LC_MESSAGES\*(C'\fR or \f(CW\*(C`LC_CTYPE\*(C'\fR.
.PP
If you need \f(CW\*(C`LC_NUMERIC\*(C'\fR, you should enable it only around the code that
actually needs it (avoiding stringification of numbers), and restore it
afterwards.
.SH "SOME HISTORY"
.IX Header "SOME HISTORY"
At the time this module was created there already were a number of \s-1JSON\s0
modules available on \s-1CPAN,\s0 so 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 handled all corner cases, and in most cases their maintainers
are unresponsive, gone missing, or not listening to bug reports for other
reasons.
.PP
Beginning with version 2.0 of the \s-1JSON\s0 module, when both \s-1JSON\s0 and
\&\s-1JSON::XS\s0 are installed, then \s-1JSON\s0 will fall back on \s-1JSON::XS \s0(this can be
overridden) with no overhead due to emulation (by inheriting constructor
and methods). If \s-1JSON::XS\s0 is not available, it will fall back to the
compatible \s-1JSON::PP\s0 module as backend, so using \s-1JSON\s0 instead of \s-1JSON::XS\s0
gives you a portable \s-1JSON API\s0 that can be fast when you need it and
doesn't require a C compiler when that is a problem.
.PP
Somewhere around version 3, this module was forked into
\&\f(CW\*(C`Cpanel::JSON::XS\*(C'\fR, because its maintainer had serious trouble
understanding \s-1JSON\s0 and insisted on a fork with many bugs \*(L"fixed\*(R" that
weren't actually bugs, while spreading \s-1FUD\s0 about this module without
actually giving any details on his accusations. You be the judge, but
in my personal opinion, if you want quality, you will stay away from
dangerous forks like that.
.SH "BUGS"
.IX Header "BUGS"
While the goal of this module is to be correct, that unfortunately does
not mean it's bug-free, only that I think its design is bug-free. If you
keep reporting bugs they will be fixed swiftly, though.
.PP
Please refrain from using rt.cpan.org or any other bug reporting
service. I put the contact address into my modules for a reason.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
The \fIjson_xs\fR command line utility for quick experiments.
.SH "AUTHOR"
.IX Header "AUTHOR"
.Vb 2
\& Marc Lehmann <schmorp@schmorp.de>
\& http://home.schmorp.de/
.Ve
SEA-GHOST - SHELL CODING BY SEA-GHOST