1XS(3)                 User Contributed Perl Documentation                XS(3)
2
3
4

NAME

6       JSON::XS - JSON serialising/deserialising, done correctly and fast
7
8       JSON::XS - XXXXXXX JSON XXXXXX/XXXXXXX
9                  (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html)
10

SYNOPSIS

12        use JSON::XS;
13
14        # exported functions, they croak on error
15        # and expect/generate UTF-8
16
17        $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
18        $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
19
20        # OO-interface
21
22        $coder = JSON::XS->new->ascii->pretty->allow_nonref;
23        $pretty_printed_unencoded = $coder->encode ($perl_scalar);
24        $perl_scalar = $coder->decode ($unicode_json_text);
25
26        # Note that JSON version 2.0 and above will automatically use JSON::XS
27        # if available, at virtually no speed overhead either, so you should
28        # be able to just:
29
30        use JSON;
31
32        # and do the same things, except that you have a pure-perl fallback now.
33

DESCRIPTION

35       This module converts Perl data structures to JSON and vice versa. Its
36       primary goal is to be correct and its secondary goal is to be fast. To
37       reach the latter goal it was written in C.
38
39       Beginning with version 2.0 of the JSON module, when both JSON and
40       JSON::XS are installed, then JSON will fall back on JSON::XS (this can
41       be overridden) with no overhead due to emulation (by inheriting
42       constructor and methods). If JSON::XS is not available, it will fall
43       back to the compatible JSON::PP module as backend, so using JSON
44       instead of JSON::XS gives you a portable JSON API that can be fast when
45       you need and doesn't require a C compiler when that is a problem.
46
47       As this is the n-th-something JSON module on CPAN, what was the reason
48       to write yet another JSON module? While it seems there are many JSON
49       modules, none of them correctly handle all corner cases, and in most
50       cases their maintainers are unresponsive, gone missing, or not
51       listening to bug reports for other reasons.
52
53       See MAPPING, below, on how JSON::XS maps perl values to JSON values and
54       vice versa.
55
56   FEATURES
57       ·   correct Unicode handling
58
59           This module knows how to handle Unicode, documents how and when it
60           does so, and even documents what "correct" means.
61
62       ·   round-trip integrity
63
64           When you serialise a perl data structure using only data types
65           supported by JSON, the deserialised data structure is identical on
66           the Perl level.  (e.g. the string "2.0" doesn't suddenly become "2"
67           just because it looks like a number). There minor are exceptions to
68           this, read the MAPPING section below to learn about those.
69
70       ·   strict checking of JSON correctness
71
72           There is no guessing, no generating of illegal JSON texts by
73           default, and only JSON is accepted as input by default (the latter
74           is a security feature).
75
76       ·   fast
77
78           Compared to other JSON modules and other serialisers such as
79           Storable, this module usually compares favourably in terms of
80           speed, too.
81
82       ·   simple to use
83
84           This module has both a simple functional interface as well as an
85           object oriented interface interface.
86
87       ·   reasonably versatile output formats
88
89           You can choose between the most compact guaranteed-single-line
90           format possible (nice for simple line-based protocols), a pure-
91           ASCII format (for when your transport is not 8-bit clean, still
92           supports the whole Unicode range), or a pretty-printed format (for
93           when you want to read that stuff). Or you can combine those
94           features in whatever way you like.
95

FUNCTIONAL INTERFACE

97       The following convenience methods are provided by this module. They are
98       exported by default:
99
100       $json_text = encode_json $perl_scalar
101           Converts the given Perl data structure to a UTF-8 encoded, binary
102           string (that is, the string contains octets only). Croaks on error.
103
104           This function call is functionally identical to:
105
106              $json_text = JSON::XS->new->utf8->encode ($perl_scalar)
107
108           Except being faster.
109
110       $perl_scalar = decode_json $json_text
111           The opposite of "encode_json": expects an UTF-8 (binary) string and
112           tries to parse that as an UTF-8 encoded JSON text, returning the
113           resulting reference. Croaks on error.
114
115           This function call is functionally identical to:
116
117              $perl_scalar = JSON::XS->new->utf8->decode ($json_text)
118
119           Except being faster.
120
121       $is_boolean = JSON::XS::is_bool $scalar
122           Returns true if the passed scalar represents either JSON::XS::true
123           or JSON::XS::false, two constants that act like 1 and 0,
124           respectively and are used to represent JSON "true" and "false"
125           values in Perl.
126
127           See MAPPING, below, for more information on how JSON values are
128           mapped to Perl.
129

A FEW NOTES ON UNICODE AND PERL

131       Since this often leads to confusion, here are a few very clear words on
132       how Unicode works in Perl, modulo bugs.
133
134       1. Perl strings can store characters with ordinal values > 255.
135           This enables you to store Unicode characters as single characters
136           in a Perl string - very natural.
137
138       2. Perl does not associate an encoding with your strings.
139           ... until you force it to, e.g. when matching it against a regex,
140           or printing the scalar to a file, in which case Perl either
141           interprets your string as locale-encoded text, octets/binary, or as
142           Unicode, depending on various settings. In no case is an encoding
143           stored together with your data, it is use that decides encoding,
144           not any magical meta data.
145
146       3. The internal utf-8 flag has no meaning with regards to the encoding
147       of your string.
148           Just ignore that flag unless you debug a Perl bug, a module written
149           in XS or want to dive into the internals of perl. Otherwise it will
150           only confuse you, as, despite the name, it says nothing about how
151           your string is encoded. You can have Unicode strings with that flag
152           set, with that flag clear, and you can have binary data with that
153           flag set and that flag clear. Other possibilities exist, too.
154
155           If you didn't know about that flag, just the better, pretend it
156           doesn't exist.
157
158       4. A "Unicode String" is simply a string where each character can be
159       validly interpreted as a Unicode code point.
160           If you have UTF-8 encoded data, it is no longer a Unicode string,
161           but a Unicode string encoded in UTF-8, giving you a binary string.
162
163       5. A string containing "high" (> 255) character values is not a UTF-8
164       string.
165           It's a fact. Learn to live with it.
166
167       I hope this helps :)
168

OBJECT-ORIENTED INTERFACE

170       The object oriented interface lets you configure your own encoding or
171       decoding style, within the limits of supported formats.
172
173       $json = new JSON::XS
174           Creates a new JSON::XS object that can be used to de/encode JSON
175           strings. All boolean flags described below are by default disabled.
176
177           The mutators for flags all return the JSON object again and thus
178           calls can be chained:
179
180              my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
181              => {"a": [1, 2]}
182
183       $json = $json->ascii ([$enable])
184       $enabled = $json->get_ascii
185           If $enable is true (or missing), then the "encode" method will not
186           generate characters outside the code range 0..127 (which is ASCII).
187           Any Unicode characters outside that range will be escaped using
188           either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL
189           escape sequence, as per RFC4627. The resulting encoded JSON text
190           can be treated as a native Unicode string, an ascii-encoded,
191           latin1-encoded or UTF-8 encoded string, or any other superset of
192           ASCII.
193
194           If $enable is false, then the "encode" method will not escape
195           Unicode characters unless required by the JSON syntax or other
196           flags. This results in a faster and more compact format.
197
198           See also the section ENCODING/CODESET FLAG NOTES later in this
199           document.
200
201           The main use for this flag is to produce JSON texts that can be
202           transmitted over a 7-bit channel, as the encoded JSON texts will
203           not contain any 8 bit characters.
204
205             JSON::XS->new->ascii (1)->encode ([chr 0x10401])
206             => ["\ud801\udc01"]
207
208       $json = $json->latin1 ([$enable])
209       $enabled = $json->get_latin1
210           If $enable is true (or missing), then the "encode" method will
211           encode the resulting JSON text as latin1 (or iso-8859-1), escaping
212           any characters outside the code range 0..255. The resulting string
213           can be treated as a latin1-encoded JSON text or a native Unicode
214           string. The "decode" method will not be affected in any way by this
215           flag, as "decode" by default expects Unicode, which is a strict
216           superset of latin1.
217
218           If $enable is false, then the "encode" method will not escape
219           Unicode characters unless required by the JSON syntax or other
220           flags.
221
222           See also the section ENCODING/CODESET FLAG NOTES later in this
223           document.
224
225           The main use for this flag is efficiently encoding binary data as
226           JSON text, as most octets will not be escaped, resulting in a
227           smaller encoded size. The disadvantage is that the resulting JSON
228           text is encoded in latin1 (and must correctly be treated as such
229           when storing and transferring), a rare encoding for JSON. It is
230           therefore most useful when you want to store data structures known
231           to contain binary data efficiently in files or databases, not when
232           talking to other JSON encoders/decoders.
233
234             JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
235             => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
236
237       $json = $json->utf8 ([$enable])
238       $enabled = $json->get_utf8
239           If $enable is true (or missing), then the "encode" method will
240           encode the JSON result into UTF-8, as required by many protocols,
241           while the "decode" method expects to be handled an UTF-8-encoded
242           string.  Please note that UTF-8-encoded strings do not contain any
243           characters outside the range 0..255, they are thus useful for
244           bytewise/binary I/O. In future versions, enabling this option might
245           enable autodetection of the UTF-16 and UTF-32 encoding families, as
246           described in RFC4627.
247
248           If $enable is false, then the "encode" method will return the JSON
249           string as a (non-encoded) Unicode string, while "decode" expects
250           thus a Unicode string.  Any decoding or encoding (e.g. to UTF-8 or
251           UTF-16) needs to be done yourself, e.g. using the Encode module.
252
253           See also the section ENCODING/CODESET FLAG NOTES later in this
254           document.
255
256           Example, output UTF-16BE-encoded JSON:
257
258             use Encode;
259             $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
260
261           Example, decode UTF-32LE-encoded JSON:
262
263             use Encode;
264             $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
265
266       $json = $json->pretty ([$enable])
267           This enables (or disables) all of the "indent", "space_before" and
268           "space_after" (and in the future possibly more) flags in one call
269           to generate the most readable (or most compact) form possible.
270
271           Example, pretty-print some simple structure:
272
273              my $json = JSON::XS->new->pretty(1)->encode ({a => [1,2]})
274              =>
275              {
276                 "a" : [
277                    1,
278                    2
279                 ]
280              }
281
282       $json = $json->indent ([$enable])
283       $enabled = $json->get_indent
284           If $enable is true (or missing), then the "encode" method will use
285           a multiline format as output, putting every array member or
286           object/hash key-value pair into its own line, indenting them
287           properly.
288
289           If $enable is false, no newlines or indenting will be produced, and
290           the resulting JSON text is guaranteed not to contain any
291           "newlines".
292
293           This setting has no effect when decoding JSON texts.
294
295       $json = $json->space_before ([$enable])
296       $enabled = $json->get_space_before
297           If $enable is true (or missing), then the "encode" method will add
298           an extra optional space before the ":" separating keys from values
299           in JSON objects.
300
301           If $enable is false, then the "encode" method will not add any
302           extra space at those places.
303
304           This setting has no effect when decoding JSON texts. You will also
305           most likely combine this setting with "space_after".
306
307           Example, space_before enabled, space_after and indent disabled:
308
309              {"key" :"value"}
310
311       $json = $json->space_after ([$enable])
312       $enabled = $json->get_space_after
313           If $enable is true (or missing), then the "encode" method will add
314           an extra optional space after the ":" separating keys from values
315           in JSON objects and extra whitespace after the "," separating key-
316           value pairs and array members.
317
318           If $enable is false, then the "encode" method will not add any
319           extra space at those places.
320
321           This setting has no effect when decoding JSON texts.
322
323           Example, space_before and indent disabled, space_after enabled:
324
325              {"key": "value"}
326
327       $json = $json->relaxed ([$enable])
328       $enabled = $json->get_relaxed
329           If $enable is true (or missing), then "decode" will accept some
330           extensions to normal JSON syntax (see below). "encode" will not be
331           affected in anyway. Be aware that this option makes you accept
332           invalid JSON texts as if they were valid!. I suggest only to use
333           this option to parse application-specific files written by humans
334           (configuration files, resource files etc.)
335
336           If $enable is false (the default), then "decode" will only accept
337           valid JSON texts.
338
339           Currently accepted extensions are:
340
341           ·   list items can have an end-comma
342
343               JSON separates array elements and key-value pairs with commas.
344               This can be annoying if you write JSON texts manually and want
345               to be able to quickly append elements, so this extension
346               accepts comma at the end of such items not just between them:
347
348                  [
349                     1,
350                     2, <- this comma not normally allowed
351                  ]
352                  {
353                     "k1": "v1",
354                     "k2": "v2", <- this comma not normally allowed
355                  }
356
357           ·   shell-style '#'-comments
358
359               Whenever JSON allows whitespace, shell-style comments are
360               additionally allowed. They are terminated by the first
361               carriage-return or line-feed character, after which more white-
362               space and comments are allowed.
363
364                 [
365                    1, # this comment not allowed in JSON
366                       # neither this one...
367                 ]
368
369       $json = $json->canonical ([$enable])
370       $enabled = $json->get_canonical
371           If $enable is true (or missing), then the "encode" method will
372           output JSON objects by sorting their keys. This is adding a
373           comparatively high overhead.
374
375           If $enable is false, then the "encode" method will output key-value
376           pairs in the order Perl stores them (which will likely change
377           between runs of the same script).
378
379           This option is useful if you want the same data structure to be
380           encoded as the same JSON text (given the same overall settings). If
381           it is disabled, the same hash might be encoded differently even if
382           contains the same data, as key-value pairs have no inherent
383           ordering in Perl.
384
385           This setting has no effect when decoding JSON texts.
386
387           This setting has currently no effect on tied hashes.
388
389       $json = $json->allow_nonref ([$enable])
390       $enabled = $json->get_allow_nonref
391           If $enable is true (or missing), then the "encode" method can
392           convert a non-reference into its corresponding string, number or
393           null JSON value, which is an extension to RFC4627. Likewise,
394           "decode" will accept those JSON values instead of croaking.
395
396           If $enable is false, then the "encode" method will croak if it
397           isn't passed an arrayref or hashref, as JSON texts must either be
398           an object or array. Likewise, "decode" will croak if given
399           something that is not a JSON object or array.
400
401           Example, encode a Perl scalar as JSON value with enabled
402           "allow_nonref", resulting in an invalid JSON text:
403
404              JSON::XS->new->allow_nonref->encode ("Hello, World!")
405              => "Hello, World!"
406
407       $json = $json->allow_unknown ([$enable])
408       $enabled = $json->get_allow_unknown
409           If $enable is true (or missing), then "encode" will not throw an
410           exception when it encounters values it cannot represent in JSON
411           (for example, filehandles) but instead will encode a JSON "null"
412           value. Note that blessed objects are not included here and are
413           handled separately by c<allow_nonref>.
414
415           If $enable is false (the default), then "encode" will throw an
416           exception when it encounters anything it cannot encode as JSON.
417
418           This option does not affect "decode" in any way, and it is
419           recommended to leave it off unless you know your communications
420           partner.
421
422       $json = $json->allow_blessed ([$enable])
423       $enabled = $json->get_allow_blessed
424           If $enable is true (or missing), then the "encode" method will not
425           barf when it encounters a blessed reference. Instead, the value of
426           the convert_blessed option will decide whether "null"
427           ("convert_blessed" disabled or no "TO_JSON" method found) or a
428           representation of the object ("convert_blessed" enabled and
429           "TO_JSON" method found) is being encoded. Has no effect on
430           "decode".
431
432           If $enable is false (the default), then "encode" will throw an
433           exception when it encounters a blessed object.
434
435       $json = $json->convert_blessed ([$enable])
436       $enabled = $json->get_convert_blessed
437           If $enable is true (or missing), then "encode", upon encountering a
438           blessed object, will check for the availability of the "TO_JSON"
439           method on the object's class. If found, it will be called in scalar
440           context and the resulting scalar will be encoded instead of the
441           object. If no "TO_JSON" method is found, the value of
442           "allow_blessed" will decide what to do.
443
444           The "TO_JSON" method may safely call die if it wants. If "TO_JSON"
445           returns other blessed objects, those will be handled in the same
446           way. "TO_JSON" must take care of not causing an endless recursion
447           cycle (== crash) in this case. The name of "TO_JSON" was chosen
448           because other methods called by the Perl core (== not by the user
449           of the object) are usually in upper case letters and to avoid
450           collisions with any "to_json" function or method.
451
452           This setting does not yet influence "decode" in any way, but in the
453           future, global hooks might get installed that influence "decode"
454           and are enabled by this setting.
455
456           If $enable is false, then the "allow_blessed" setting will decide
457           what to do when a blessed object is found.
458
459       $json = $json->filter_json_object ([$coderef->($hashref)])
460           When $coderef is specified, it will be called from "decode" each
461           time it decodes a JSON object. The only argument is a reference to
462           the newly-created hash. If the code references returns a single
463           scalar (which need not be a reference), this value (i.e. a copy of
464           that scalar to avoid aliasing) is inserted into the deserialised
465           data structure. If it returns an empty list (NOTE: not "undef",
466           which is a valid scalar), the original deserialised hash will be
467           inserted. This setting can slow down decoding considerably.
468
469           When $coderef is omitted or undefined, any existing callback will
470           be removed and "decode" will not change the deserialised hash in
471           any way.
472
473           Example, convert all JSON objects into the integer 5:
474
475              my $js = JSON::XS->new->filter_json_object (sub { 5 });
476              # returns [5]
477              $js->decode ('[{}]')
478              # throw an exception because allow_nonref is not enabled
479              # so a lone 5 is not allowed.
480              $js->decode ('{"a":1, "b":2}');
481
482       $json = $json->filter_json_single_key_object ($key [=>
483       $coderef->($value)])
484           Works remotely similar to "filter_json_object", but is only called
485           for JSON objects having a single key named $key.
486
487           This $coderef is called before the one specified via
488           "filter_json_object", if any. It gets passed the single value in
489           the JSON object. If it returns a single value, it will be inserted
490           into the data structure. If it returns nothing (not even "undef"
491           but the empty list), the callback from "filter_json_object" will be
492           called next, as if no single-key callback were specified.
493
494           If $coderef is omitted or undefined, the corresponding callback
495           will be disabled. There can only ever be one callback for a given
496           key.
497
498           As this callback gets called less often then the
499           "filter_json_object" one, decoding speed will not usually suffer as
500           much. Therefore, single-key objects make excellent targets to
501           serialise Perl objects into, especially as single-key JSON objects
502           are as close to the type-tagged value concept as JSON gets (it's
503           basically an ID/VALUE tuple). Of course, JSON does not support this
504           in any way, so you need to make sure your data never looks like a
505           serialised Perl hash.
506
507           Typical names for the single object key are "__class_whatever__",
508           or "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or
509           even things like "__class_md5sum(classname)__", to reduce the risk
510           of clashing with real hashes.
511
512           Example, decode JSON objects of the form "{ "__widget__" => <id> }"
513           into the corresponding $WIDGET{<id>} object:
514
515              # return whatever is in $WIDGET{5}:
516              JSON::XS
517                 ->new
518                 ->filter_json_single_key_object (__widget__ => sub {
519                       $WIDGET{ $_[0] }
520                    })
521                 ->decode ('{"__widget__": 5')
522
523              # this can be used with a TO_JSON method in some "widget" class
524              # for serialisation to json:
525              sub WidgetBase::TO_JSON {
526                 my ($self) = @_;
527
528                 unless ($self->{id}) {
529                    $self->{id} = ..get..some..id..;
530                    $WIDGET{$self->{id}} = $self;
531                 }
532
533                 { __widget__ => $self->{id} }
534              }
535
536       $json = $json->shrink ([$enable])
537       $enabled = $json->get_shrink
538           Perl usually over-allocates memory a bit when allocating space for
539           strings. This flag optionally resizes strings generated by either
540           "encode" or "decode" to their minimum size possible. This can save
541           memory when your JSON texts are either very very long or you have
542           many short strings. It will also try to downgrade any strings to
543           octet-form if possible: perl stores strings internally either in an
544           encoding called UTF-X or in octet-form. The latter cannot store
545           everything but uses less space in general (and some buggy Perl or C
546           code might even rely on that internal representation being used).
547
548           The actual definition of what shrink does might change in future
549           versions, but it will always try to save space at the expense of
550           time.
551
552           If $enable is true (or missing), the string returned by "encode"
553           will be shrunk-to-fit, while all strings generated by "decode" will
554           also be shrunk-to-fit.
555
556           If $enable is false, then the normal perl allocation algorithms are
557           used.  If you work with your data, then this is likely to be
558           faster.
559
560           In the future, this setting might control other things, such as
561           converting strings that look like integers or floats into integers
562           or floats internally (there is no difference on the Perl level),
563           saving space.
564
565       $json = $json->max_depth ([$maximum_nesting_depth])
566       $max_depth = $json->get_max_depth
567           Sets the maximum nesting level (default 512) accepted while
568           encoding or decoding. If a higher nesting level is detected in JSON
569           text or a Perl data structure, then the encoder and decoder will
570           stop and croak at that point.
571
572           Nesting level is defined by number of hash- or arrayrefs that the
573           encoder needs to traverse to reach a given point or the number of
574           "{" or "[" characters without their matching closing parenthesis
575           crossed to reach a given character in a string.
576
577           Setting the maximum depth to one disallows any nesting, so that
578           ensures that the object is only a single hash/object or array.
579
580           If no argument is given, the highest possible setting will be used,
581           which is rarely useful.
582
583           Note that nesting is implemented by recursion in C. The default
584           value has been chosen to be as large as typical operating systems
585           allow without crashing.
586
587           See SECURITY CONSIDERATIONS, below, for more info on why this is
588           useful.
589
590       $json = $json->max_size ([$maximum_string_size])
591       $max_size = $json->get_max_size
592           Set the maximum length a JSON text may have (in bytes) where
593           decoding is being attempted. The default is 0, meaning no limit.
594           When "decode" is called on a string that is longer then this many
595           bytes, it will not attempt to decode the string but throw an
596           exception. This setting has no effect on "encode" (yet).
597
598           If no argument is given, the limit check will be deactivated (same
599           as when 0 is specified).
600
601           See SECURITY CONSIDERATIONS, below, for more info on why this is
602           useful.
603
604       $json_text = $json->encode ($perl_scalar)
605           Converts the given Perl data structure (a simple scalar or a
606           reference to a hash or array) to its JSON representation. Simple
607           scalars will be converted into JSON string or number sequences,
608           while references to arrays become JSON arrays and references to
609           hashes become JSON objects. Undefined Perl values (e.g. "undef")
610           become JSON "null" values. Neither "true" nor "false" values will
611           be generated.
612
613       $perl_scalar = $json->decode ($json_text)
614           The opposite of "encode": expects a JSON text and tries to parse
615           it, returning the resulting simple scalar or reference. Croaks on
616           error.
617
618           JSON numbers and strings become simple Perl scalars. JSON arrays
619           become Perl arrayrefs and JSON objects become Perl hashrefs. "true"
620           becomes 1, "false" becomes 0 and "null" becomes "undef".
621
622       ($perl_scalar, $characters) = $json->decode_prefix ($json_text)
623           This works like the "decode" method, but instead of raising an
624           exception when there is trailing garbage after the first JSON
625           object, it will silently stop parsing there and return the number
626           of characters consumed so far.
627
628           This is useful if your JSON texts are not delimited by an outer
629           protocol (which is not the brightest thing to do in the first
630           place) and you need to know where the JSON text ends.
631
632              JSON::XS->new->decode_prefix ("[1] the tail")
633              => ([], 3)
634

INCREMENTAL PARSING

636       In some cases, there is the need for incremental parsing of JSON texts.
637       While this module always has to keep both JSON text and resulting Perl
638       data structure in memory at one time, it does allow you to parse a JSON
639       stream incrementally. It does so by accumulating text until it has a
640       full JSON object, which it then can decode. This process is similar to
641       using "decode_prefix" to see if a full JSON object is available, but is
642       much more efficient (and can be implemented with a minimum of method
643       calls).
644
645       JSON::XS will only attempt to parse the JSON text once it is sure it
646       has enough text to get a decisive result, using a very simple but truly
647       incremental parser. This means that it sometimes won't stop as early as
648       the full parser, for example, it doesn't detect parenthese mismatches.
649       The only thing it guarantees is that it starts decoding as soon as a
650       syntactically valid JSON text has been seen. This means you need to set
651       resource limits (e.g. "max_size") to ensure the parser will stop
652       parsing in the presence if syntax errors.
653
654       The following methods implement this incremental parser.
655
656       [void, scalar or list context] = $json->incr_parse ([$string])
657           This is the central parsing function. It can both append new text
658           and extract objects from the stream accumulated so far (both of
659           these functions are optional).
660
661           If $string is given, then this string is appended to the already
662           existing JSON fragment stored in the $json object.
663
664           After that, if the function is called in void context, it will
665           simply return without doing anything further. This can be used to
666           add more text in as many chunks as you want.
667
668           If the method is called in scalar context, then it will try to
669           extract exactly one JSON object. If that is successful, it will
670           return this object, otherwise it will return "undef". If there is a
671           parse error, this method will croak just as "decode" would do (one
672           can then use "incr_skip" to skip the errornous part). This is the
673           most common way of using the method.
674
675           And finally, in list context, it will try to extract as many
676           objects from the stream as it can find and return them, or the
677           empty list otherwise. For this to work, there must be no separators
678           between the JSON objects or arrays, instead they must be
679           concatenated back-to-back. If an error occurs, an exception will be
680           raised as in the scalar context case. Note that in this case, any
681           previously-parsed JSON texts will be lost.
682
683       $lvalue_string = $json->incr_text
684           This method returns the currently stored JSON fragment as an
685           lvalue, that is, you can manipulate it. This only works when a
686           preceding call to "incr_parse" in scalar context successfully
687           returned an object. Under all other circumstances you must not call
688           this function (I mean it.  although in simple tests it might
689           actually work, it will fail under real world conditions). As a
690           special exception, you can also call this method before having
691           parsed anything.
692
693           This function is useful in two cases: a) finding the trailing text
694           after a JSON object or b) parsing multiple JSON objects separated
695           by non-JSON text (such as commas).
696
697       $json->incr_skip
698           This will reset the state of the incremental parser and will remove
699           the parsed text from the input buffer so far. This is useful after
700           "incr_parse" died, in which case the input buffer and incremental
701           parser state is left unchanged, to skip the text parsed so far and
702           to reset the parse state.
703
704           The difference to "incr_reset" is that only text until the parse
705           error occured is removed.
706
707       $json->incr_reset
708           This completely resets the incremental parser, that is, after this
709           call, it will be as if the parser had never parsed anything.
710
711           This is useful if you want to repeatedly parse JSON objects and
712           want to ignore any trailing data, which means you have to reset the
713           parser after each successful decode.
714
715   LIMITATIONS
716       All options that affect decoding are supported, except "allow_nonref".
717       The reason for this is that it cannot be made to work sensibly: JSON
718       objects and arrays are self-delimited, i.e. you can concatenate them
719       back to back and still decode them perfectly. This does not hold true
720       for JSON numbers, however.
721
722       For example, is the string 1 a single JSON number, or is it simply the
723       start of 12? Or is 12 a single JSON number, or the concatenation of 1
724       and 2? In neither case you can tell, and this is why JSON::XS takes the
725       conservative route and disallows this case.
726
727   EXAMPLES
728       Some examples will make all this clearer. First, a simple example that
729       works similarly to "decode_prefix": We want to decode the JSON object
730       at the start of a string and identify the portion after the JSON
731       object:
732
733          my $text = "[1,2,3] hello";
734
735          my $json = new JSON::XS;
736
737          my $obj = $json->incr_parse ($text)
738             or die "expected JSON object or array at beginning of string";
739
740          my $tail = $json->incr_text;
741          # $tail now contains " hello"
742
743       Easy, isn't it?
744
745       Now for a more complicated example: Imagine a hypothetical protocol
746       where you read some requests from a TCP stream, and each request is a
747       JSON array, without any separation between them (in fact, it is often
748       useful to use newlines as "separators", as these get interpreted as
749       whitespace at the start of the JSON text, which makes it possible to
750       test said protocol with "telnet"...).
751
752       Here is how you'd do it (it is trivial to write this in an event-based
753       manner):
754
755          my $json = new JSON::XS;
756
757          # read some data from the socket
758          while (sysread $socket, my $buf, 4096) {
759
760             # split and decode as many requests as possible
761             for my $request ($json->incr_parse ($buf)) {
762                # act on the $request
763             }
764          }
765
766       Another complicated example: Assume you have a string with JSON objects
767       or arrays, all separated by (optional) comma characters (e.g. "[1],[2],
768       [3]"). To parse them, we have to skip the commas between the JSON
769       texts, and here is where the lvalue-ness of "incr_text" comes in
770       useful:
771
772          my $text = "[1],[2], [3]";
773          my $json = new JSON::XS;
774
775          # void context, so no parsing done
776          $json->incr_parse ($text);
777
778          # now extract as many objects as possible. note the
779          # use of scalar context so incr_text can be called.
780          while (my $obj = $json->incr_parse) {
781             # do something with $obj
782
783             # now skip the optional comma
784             $json->incr_text =~ s/^ \s* , //x;
785          }
786
787       Now lets go for a very complex example: Assume that you have a gigantic
788       JSON array-of-objects, many gigabytes in size, and you want to parse
789       it, but you cannot load it into memory fully (this has actually
790       happened in the real world :).
791
792       Well, you lost, you have to implement your own JSON parser. But
793       JSON::XS can still help you: You implement a (very simple) array parser
794       and let JSON decode the array elements, which are all full JSON objects
795       on their own (this wouldn't work if the array elements could be JSON
796       numbers, for example):
797
798          my $json = new JSON::XS;
799
800          # open the monster
801          open my $fh, "<bigfile.json"
802             or die "bigfile: $!";
803
804          # first parse the initial "["
805          for (;;) {
806             sysread $fh, my $buf, 65536
807                or die "read error: $!";
808             $json->incr_parse ($buf); # void context, so no parsing
809
810             # Exit the loop once we found and removed(!) the initial "[".
811             # In essence, we are (ab-)using the $json object as a simple scalar
812             # we append data to.
813             last if $json->incr_text =~ s/^ \s* \[ //x;
814          }
815
816          # now we have the skipped the initial "[", so continue
817          # parsing all the elements.
818          for (;;) {
819             # in this loop we read data until we got a single JSON object
820             for (;;) {
821                if (my $obj = $json->incr_parse) {
822                   # do something with $obj
823                   last;
824                }
825
826                # add more data
827                sysread $fh, my $buf, 65536
828                   or die "read error: $!";
829                $json->incr_parse ($buf); # void context, so no parsing
830             }
831
832             # in this loop we read data until we either found and parsed the
833             # separating "," between elements, or the final "]"
834             for (;;) {
835                # first skip whitespace
836                $json->incr_text =~ s/^\s*//;
837
838                # if we find "]", we are done
839                if ($json->incr_text =~ s/^\]//) {
840                   print "finished.\n";
841                   exit;
842                }
843
844                # if we find ",", we can continue with the next element
845                if ($json->incr_text =~ s/^,//) {
846                   last;
847                }
848
849                # if we find anything else, we have a parse error!
850                if (length $json->incr_text) {
851                   die "parse error near ", $json->incr_text;
852                }
853
854                # else add more data
855                sysread $fh, my $buf, 65536
856                   or die "read error: $!";
857                $json->incr_parse ($buf); # void context, so no parsing
858             }
859
860       This is a complex example, but most of the complexity comes from the
861       fact that we are trying to be correct (bear with me if I am wrong, I
862       never ran the above example :).
863

MAPPING

865       This section describes how JSON::XS maps Perl values to JSON values and
866       vice versa. These mappings are designed to "do the right thing" in most
867       circumstances automatically, preserving round-tripping characteristics
868       (what you put in comes out as something equivalent).
869
870       For the more enlightened: note that in the following descriptions,
871       lowercase perl refers to the Perl interpreter, while uppercase Perl
872       refers to the abstract Perl language itself.
873
874   JSON -> PERL
875       object
876           A JSON object becomes a reference to a hash in Perl. No ordering of
877           object keys is preserved (JSON does not preserve object key
878           ordering itself).
879
880       array
881           A JSON array becomes a reference to an array in Perl.
882
883       string
884           A JSON string becomes a string scalar in Perl - Unicode codepoints
885           in JSON are represented by the same codepoints in the Perl string,
886           so no manual decoding is necessary.
887
888       number
889           A JSON number becomes either an integer, numeric (floating point)
890           or string scalar in perl, depending on its range and any fractional
891           parts. On the Perl level, there is no difference between those as
892           Perl handles all the conversion details, but an integer may take
893           slightly less memory and might represent more values exactly than
894           floating point numbers.
895
896           If the number consists of digits only, JSON::XS will try to
897           represent it as an integer value. If that fails, it will try to
898           represent it as a numeric (floating point) value if that is
899           possible without loss of precision. Otherwise it will preserve the
900           number as a string value (in which case you lose roundtripping
901           ability, as the JSON number will be re-encoded toa JSON string).
902
903           Numbers containing a fractional or exponential part will always be
904           represented as numeric (floating point) values, possibly at a loss
905           of precision (in which case you might lose perfect roundtripping
906           ability, but the JSON number will still be re-encoded as a JSON
907           number).
908
909       true, false
910           These JSON atoms become "JSON::XS::true" and "JSON::XS::false",
911           respectively. They are overloaded to act almost exactly like the
912           numbers 1 and 0. You can check whether a scalar is a JSON boolean
913           by using the "JSON::XS::is_bool" function.
914
915       null
916           A JSON null atom becomes "undef" in Perl.
917
918   PERL -> JSON
919       The mapping from Perl to JSON is slightly more difficult, as Perl is a
920       truly typeless language, so we can only guess which JSON type is meant
921       by a Perl value.
922
923       hash references
924           Perl hash references become JSON objects. As there is no inherent
925           ordering in hash keys (or JSON objects), they will usually be
926           encoded in a pseudo-random order that can change between runs of
927           the same program but stays generally the same within a single run
928           of a program. JSON::XS can optionally sort the hash keys
929           (determined by the canonical flag), so the same datastructure will
930           serialise to the same JSON text (given same settings and version of
931           JSON::XS), but this incurs a runtime overhead and is only rarely
932           useful, e.g. when you want to compare some JSON text against
933           another for equality.
934
935       array references
936           Perl array references become JSON arrays.
937
938       other references
939           Other unblessed references are generally not allowed and will cause
940           an exception to be thrown, except for references to the integers 0
941           and 1, which get turned into "false" and "true" atoms in JSON. You
942           can also use "JSON::XS::false" and "JSON::XS::true" to improve
943           readability.
944
945              encode_json [\0, JSON::XS::true]      # yields [false,true]
946
947       JSON::XS::true, JSON::XS::false
948           These special values become JSON true and JSON false values,
949           respectively. You can also use "\1" and "\0" directly if you want.
950
951       blessed objects
952           Blessed objects are not directly representable in JSON. See the
953           "allow_blessed" and "convert_blessed" methods on various options on
954           how to deal with this: basically, you can choose between throwing
955           an exception, encoding the reference as if it weren't blessed, or
956           provide your own serialiser method.
957
958       simple scalars
959           Simple Perl scalars (any scalar that is not a reference) are the
960           most difficult objects to encode: JSON::XS will encode undefined
961           scalars as JSON "null" values, scalars that have last been used in
962           a string context before encoding as JSON strings, and anything else
963           as number value:
964
965              # dump as number
966              encode_json [2]                      # yields [2]
967              encode_json [-3.0e17]                # yields [-3e+17]
968              my $value = 5; encode_json [$value]  # yields [5]
969
970              # used as string, so dump as string
971              print $value;
972              encode_json [$value]                 # yields ["5"]
973
974              # undef becomes null
975              encode_json [undef]                  # yields [null]
976
977           You can force the type to be a JSON string by stringifying it:
978
979              my $x = 3.1; # some variable containing a number
980              "$x";        # stringified
981              $x .= "";    # another, more awkward way to stringify
982              print $x;    # perl does it for you, too, quite often
983
984           You can force the type to be a JSON number by numifying it:
985
986              my $x = "3"; # some variable containing a string
987              $x += 0;     # numify it, ensuring it will be dumped as a number
988              $x *= 1;     # same thing, the choice is yours.
989
990           You can not currently force the type in other, less obscure, ways.
991           Tell me if you need this capability (but don't forget to explain
992           why it's needed :).
993

ENCODING/CODESET FLAG NOTES

995       The interested reader might have seen a number of flags that signify
996       encodings or codesets - "utf8", "latin1" and "ascii". There seems to be
997       some confusion on what these do, so here is a short comparison:
998
999       "utf8" controls whether the JSON text created by "encode" (and expected
1000       by "decode") is UTF-8 encoded or not, while "latin1" and "ascii" only
1001       control whether "encode" escapes character values outside their
1002       respective codeset range. Neither of these flags conflict with each
1003       other, although some combinations make less sense than others.
1004
1005       Care has been taken to make all flags symmetrical with respect to
1006       "encode" and "decode", that is, texts encoded with any combination of
1007       these flag values will be correctly decoded when the same flags are
1008       used - in general, if you use different flag settings while encoding
1009       vs. when decoding you likely have a bug somewhere.
1010
1011       Below comes a verbose discussion of these flags. Note that a "codeset"
1012       is simply an abstract set of character-codepoint pairs, while an
1013       encoding takes those codepoint numbers and encodes them, in our case
1014       into octets. Unicode is (among other things) a codeset, UTF-8 is an
1015       encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets and
1016       encodings at the same time, which can be confusing.
1017
1018       "utf8" flag disabled
1019           When "utf8" is disabled (the default), then "encode"/"decode"
1020           generate and expect Unicode strings, that is, characters with high
1021           ordinal Unicode values (> 255) will be encoded as such characters,
1022           and likewise such characters are decoded as-is, no canges to them
1023           will be done, except "(re-)interpreting" them as Unicode codepoints
1024           or Unicode characters, respectively (to Perl, these are the same
1025           thing in strings unless you do funny/weird/dumb stuff).
1026
1027           This is useful when you want to do the encoding yourself (e.g. when
1028           you want to have UTF-16 encoded JSON texts) or when some other
1029           layer does the encoding for you (for example, when printing to a
1030           terminal using a filehandle that transparently encodes to UTF-8 you
1031           certainly do NOT want to UTF-8 encode your data first and have Perl
1032           encode it another time).
1033
1034       "utf8" flag enabled
1035           If the "utf8"-flag is enabled, "encode"/"decode" will encode all
1036           characters using the corresponding UTF-8 multi-byte sequence, and
1037           will expect your input strings to be encoded as UTF-8, that is, no
1038           "character" of the input string must have any value > 255, as UTF-8
1039           does not allow that.
1040
1041           The "utf8" flag therefore switches between two modes: disabled
1042           means you will get a Unicode string in Perl, enabled means you get
1043           an UTF-8 encoded octet/binary string in Perl.
1044
1045       "latin1" or "ascii" flags enabled
1046           With "latin1" (or "ascii") enabled, "encode" will escape characters
1047           with ordinal values > 255 (> 127 with "ascii") and encode the
1048           remaining characters as specified by the "utf8" flag.
1049
1050           If "utf8" is disabled, then the result is also correctly encoded in
1051           those character sets (as both are proper subsets of Unicode,
1052           meaning that a Unicode string with all character values < 256 is
1053           the same thing as a ISO-8859-1 string, and a Unicode string with
1054           all character values < 128 is the same thing as an ASCII string in
1055           Perl).
1056
1057           If "utf8" is enabled, you still get a correct UTF-8-encoded string,
1058           regardless of these flags, just some more characters will be
1059           escaped using "\uXXXX" then before.
1060
1061           Note that ISO-8859-1-encoded strings are not compatible with UTF-8
1062           encoding, while ASCII-encoded strings are. That is because the
1063           ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the
1064           ISO-8859-1 codeset being a subset of Unicode), while ASCII is.
1065
1066           Surprisingly, "decode" will ignore these flags and so treat all
1067           input values as governed by the "utf8" flag. If it is disabled,
1068           this allows you to decode ISO-8859-1- and ASCII-encoded strings, as
1069           both strict subsets of Unicode. If it is enabled, you can correctly
1070           decode UTF-8 encoded strings.
1071
1072           So neither "latin1" nor "ascii" are incompatible with the "utf8"
1073           flag - they only govern when the JSON output engine escapes a
1074           character or not.
1075
1076           The main use for "latin1" is to relatively efficiently store binary
1077           data as JSON, at the expense of breaking compatibility with most
1078           JSON decoders.
1079
1080           The main use for "ascii" is to force the output to not contain
1081           characters with values > 127, which means you can interpret the
1082           resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about
1083           any character set and 8-bit-encoding, and still get the same data
1084           structure back. This is useful when your channel for JSON transfer
1085           is not 8-bit clean or the encoding might be mangled in between
1086           (e.g. in mail), and works because ASCII is a proper subset of most
1087           8-bit and multibyte encodings in use in the world.
1088
1089   JSON and ECMAscript
1090       JSON syntax is based on how literals are represented in javascript (the
1091       not-standardised predecessor of ECMAscript) which is presumably why it
1092       is called "JavaScript Object Notation".
1093
1094       However, JSON is not a subset (and also not a superset of course) of
1095       ECMAscript (the standard) or javascript (whatever browsers actually
1096       implement).
1097
1098       If you want to use javascript's "eval" function to "parse" JSON, you
1099       might run into parse errors for valid JSON texts, or the resulting data
1100       structure might not be queryable:
1101
1102       One of the problems is that U+2028 and U+2029 are valid characters
1103       inside JSON strings, but are not allowed in ECMAscript string literals,
1104       so the following Perl fragment will not output something that can be
1105       guaranteed to be parsable by javascript's "eval":
1106
1107          use JSON::XS;
1108
1109          print encode_json [chr 0x2028];
1110
1111       The right fix for this is to use a proper JSON parser in your
1112       javascript programs, and not rely on "eval" (see for example Douglas
1113       Crockford's json2.js parser).
1114
1115       If this is not an option, you can, as a stop-gap measure, simply encode
1116       to ASCII-only JSON:
1117
1118          use JSON::XS;
1119
1120          print JSON::XS->new->ascii->encode ([chr 0x2028]);
1121
1122       Note that this will enlarge the resulting JSON text quite a bit if you
1123       have many non-ASCII characters. You might be tempted to run some
1124       regexes to only escape U+2028 and U+2029, e.g.:
1125
1126          # DO NOT USE THIS!
1127          my $json = JSON::XS->new->utf8->encode ([chr 0x2028]);
1128          $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028
1129          $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029
1130          print $json;
1131
1132       Note that this is a bad idea: the above only works for U+2028 and
1133       U+2029 and thus only for fully ECMAscript-compliant parsers. Many
1134       existing javascript implementations, however, have issues with other
1135       characters as well - using "eval" naively simply will cause problems.
1136
1137       Another problem is that some javascript implementations reserve some
1138       property names for their own purposes (which probably makes them non-
1139       ECMAscript-compliant). For example, Iceweasel reserves the "__proto__"
1140       property name for it's own purposes.
1141
1142       If that is a problem, you could parse try to filter the resulting JSON
1143       output for these property strings, e.g.:
1144
1145          $json =~ s/"__proto__"\s*:/"__proto__renamed":/g;
1146
1147       This works because "__proto__" is not valid outside of strings, so
1148       every occurence of ""__proto__"\s*:" must be a string used as property
1149       name.
1150
1151       If you know of other incompatibilities, please let me know.
1152
1153   JSON and YAML
1154       You often hear that JSON is a subset of YAML. This is, however, a mass
1155       hysteria(*) and very far from the truth (as of the time of this
1156       writing), so let me state it clearly: in general, there is no way to
1157       configure JSON::XS to output a data structure as valid YAML that works
1158       in all cases.
1159
1160       If you really must use JSON::XS to generate YAML, you should use this
1161       algorithm (subject to change in future versions):
1162
1163          my $to_yaml = JSON::XS->new->utf8->space_after (1);
1164          my $yaml = $to_yaml->encode ($ref) . "\n";
1165
1166       This will usually generate JSON texts that also parse as valid YAML.
1167       Please note that YAML has hardcoded limits on (simple) object key
1168       lengths that JSON doesn't have and also has different and incompatible
1169       unicode character escape syntax, so you should make sure that your hash
1170       keys are noticeably shorter than the 1024 "stream characters" YAML
1171       allows and that you do not have characters with codepoint values
1172       outside the Unicode BMP (basic multilingual page). YAML also does not
1173       allow "\/" sequences in strings (which JSON::XS does not currently
1174       generate, but other JSON generators might).
1175
1176       There might be other incompatibilities that I am not aware of (or the
1177       YAML specification has been changed yet again - it does so quite
1178       often). In general you should not try to generate YAML with a JSON
1179       generator or vice versa, or try to parse JSON with a YAML parser or
1180       vice versa: chances are high that you will run into severe
1181       interoperability problems when you least expect it.
1182
1183       (*) I have been pressured multiple times by Brian Ingerson (one of the
1184           authors of the YAML specification) to remove this paragraph,
1185           despite him acknowledging that the actual incompatibilities exist.
1186           As I was personally bitten by this "JSON is YAML" lie, I refused
1187           and said I will continue to educate people about these issues, so
1188           others do not run into the same problem again and again. After
1189           this, Brian called me a (quote)complete and worthless
1190           idiot(unquote).
1191
1192           In my opinion, instead of pressuring and insulting people who
1193           actually clarify issues with YAML and the wrong statements of some
1194           of its proponents, I would kindly suggest reading the JSON spec
1195           (which is not that difficult or long) and finally make YAML
1196           compatible to it, and educating users about the changes, instead of
1197           spreading lies about the real compatibility for many years and
1198           trying to silence people who point out that it isn't true.
1199
1200           Addendum/2009: the YAML 1.2 spec is still incomaptible with JSON,
1201           even though the incompatibilities have been documented (and are
1202           known to Brian) for many years and the spec makes explicit claims
1203           that YAML is a superset of JSON. It would be so easy to fix, but
1204           apparently, bullying and corrupting userdata is so much easier.
1205
1206   SPEED
1207       It seems that JSON::XS is surprisingly fast, as shown in the following
1208       tables. They have been generated with the help of the "eg/bench"
1209       program in the JSON::XS distribution, to make it easy to compare on
1210       your own system.
1211
1212       First comes a comparison between various modules using a very short
1213       single-line JSON string (also available at
1214       <http://dist.schmorp.de/misc/json/short.json>).
1215
1216          {"method": "handleMessage", "params": ["user1",
1217          "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7,
1218          true,  false]}
1219
1220       It shows the number of encodes/decodes per second (JSON::XS uses the
1221       functional interface, while JSON::XS/2 uses the OO interface with
1222       pretty-printing and hashkey sorting enabled, JSON::XS/3 enables
1223       shrink). Higher is better:
1224
1225          module     |     encode |     decode |
1226          -----------|------------|------------|
1227          JSON 1.x   |   4990.842 |   4088.813 |
1228          JSON::DWIW |  51653.990 |  71575.154 |
1229          JSON::PC   |  65948.176 |  74631.744 |
1230          JSON::PP   |   8931.652 |   3817.168 |
1231          JSON::Syck |  24877.248 |  27776.848 |
1232          JSON::XS   | 388361.481 | 227951.304 |
1233          JSON::XS/2 | 227951.304 | 218453.333 |
1234          JSON::XS/3 | 338250.323 | 218453.333 |
1235          Storable   |  16500.016 | 135300.129 |
1236          -----------+------------+------------+
1237
1238       That is, JSON::XS is about five times faster than JSON::DWIW on
1239       encoding, about three times faster on decoding, and over forty times
1240       faster than JSON, even with pretty-printing and key sorting. It also
1241       compares favourably to Storable for small amounts of data.
1242
1243       Using a longer test string (roughly 18KB, generated from Yahoo! Locals
1244       search API (<http://dist.schmorp.de/misc/json/long.json>).
1245
1246          module     |     encode |     decode |
1247          -----------|------------|------------|
1248          JSON 1.x   |     55.260 |     34.971 |
1249          JSON::DWIW |    825.228 |   1082.513 |
1250          JSON::PC   |   3571.444 |   2394.829 |
1251          JSON::PP   |    210.987 |     32.574 |
1252          JSON::Syck |    552.551 |    787.544 |
1253          JSON::XS   |   5780.463 |   4854.519 |
1254          JSON::XS/2 |   3869.998 |   4798.975 |
1255          JSON::XS/3 |   5862.880 |   4798.975 |
1256          Storable   |   4445.002 |   5235.027 |
1257          -----------+------------+------------+
1258
1259       Again, JSON::XS leads by far (except for Storable which non-
1260       surprisingly decodes faster).
1261
1262       On large strings containing lots of high Unicode characters, some
1263       modules (such as JSON::PC) seem to decode faster than JSON::XS, but the
1264       result will be broken due to missing (or wrong) Unicode handling.
1265       Others refuse to decode or encode properly, so it was impossible to
1266       prepare a fair comparison table for that case.
1267

SECURITY CONSIDERATIONS

1269       When you are using JSON in a protocol, talking to untrusted potentially
1270       hostile creatures requires relatively few measures.
1271
1272       First of all, your JSON decoder should be secure, that is, should not
1273       have any buffer overflows. Obviously, this module should ensure that
1274       and I am trying hard on making that true, but you never know.
1275
1276       Second, you need to avoid resource-starving attacks. That means you
1277       should limit the size of JSON texts you accept, or make sure then when
1278       your resources run out, that's just fine (e.g. by using a separate
1279       process that can crash safely). The size of a JSON text in octets or
1280       characters is usually a good indication of the size of the resources
1281       required to decode it into a Perl structure. While JSON::XS can check
1282       the size of the JSON text, it might be too late when you already have
1283       it in memory, so you might want to check the size before you accept the
1284       string.
1285
1286       Third, JSON::XS recurses using the C stack when decoding objects and
1287       arrays. The C stack is a limited resource: for instance, on my amd64
1288       machine with 8MB of stack size I can decode around 180k nested arrays
1289       but only 14k nested JSON objects (due to perl itself recursing deeply
1290       on croak to free the temporary). If that is exceeded, the program
1291       crashes. To be conservative, the default nesting limit is set to 512.
1292       If your process has a smaller stack, you should adjust this setting
1293       accordingly with the "max_depth" method.
1294
1295       Something else could bomb you, too, that I forgot to think of. In that
1296       case, you get to keep the pieces. I am always open for hints, though...
1297
1298       Also keep in mind that JSON::XS might leak contents of your Perl data
1299       structures in its error messages, so when you serialise sensitive
1300       information you might want to make sure that exceptions thrown by
1301       JSON::XS will not end up in front of untrusted eyes.
1302
1303       If you are using JSON::XS to return packets to consumption by
1304       JavaScript scripts in a browser you should have a look at
1305       http://jpsykes.com/47/practical-csrf-and-json-security
1306       <http://jpsykes.com/47/practical-csrf-and-json-security> to see whether
1307       you are vulnerable to some common attack vectors (which really are
1308       browser design bugs, but it is still you who will have to deal with it,
1309       as major browser developers care only for features, not about getting
1310       security right).
1311

THREADS

1313       This module is not guaranteed to be thread safe and there are no plans
1314       to change this until Perl gets thread support (as opposed to the
1315       horribly slow so-called "threads" which are simply slow and bloated
1316       process simulations - use fork, it's much faster, cheaper, better).
1317
1318       (It might actually work, but you have been warned).
1319

BUGS

1321       While the goal of this module is to be correct, that unfortunately does
1322       not mean it's bug-free, only that I think its design is bug-free. If
1323       you keep reporting bugs they will be fixed swiftly, though.
1324
1325       Please refrain from using rt.cpan.org or any other bug reporting
1326       service. I put the contact address into my modules for a reason.
1327

SEE ALSO

1329       The json_xs command line utility for quick experiments.
1330

AUTHOR

1332        Marc Lehmann <schmorp@schmorp.de>
1333        http://home.schmorp.de/
1334
1335
1336
1337perl v5.12.0                      2010-01-06                             XS(3)
Impressum