1NAME
2 JSON - JSON (JavaScript Object Notation) encoder/decoder
3
4SYNOPSIS
5 use JSON; # imports encode_json, decode_json, to_json and from_json.
6
7 # simple and fast interfaces (expect/generate UTF-8)
8
9 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
10 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
11
12 # OO-interface
13
14 $json = JSON->new->allow_nonref;
15
16 $json_text = $json->encode( $perl_scalar );
17 $perl_scalar = $json->decode( $json_text );
18
19 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
20
21VERSION
22 2.93
23
24DESCRIPTION
25 This module is a thin wrapper for JSON::XS-compatible modules with
26 a few additional features. All the backend modules convert a Perl
27 data structure to a JSON text as of RFC4627 (which we know is
28 obsolete but we still stick to; see below for an option to support
29 part of RFC7159) and vice versa. This module uses JSON::XS by
30 default, and when JSON::XS is not available, this module falls
31 back on JSON::PP, which is in the Perl core since 5.14. If
32 JSON::PP is not available either, this module then falls back on
33 JSON::backportPP (which is actually JSON::PP in a different .pm
34 file) bundled in the same distribution as this module. You can
35 also explicitly specify to use Cpanel::JSON::XS, a fork of
36 JSON::XS by Reini Urban.
37
38 All these backend modules have slight incompatibilities between
39 them, including extra features that other modules don't support,
40 but as long as you use only common features (most important ones
41 are described below), migration from backend to backend should be
42 reasonably easy. For details, see each backend module you use.
43
44CHOOSING BACKEND
45 This module respects an environmental variable called
46 "PERL_JSON_BACKEND" when it decides a backend module to use. If
47 this environmental variable is not set, it tries to load JSON::XS,
48 and if JSON::XS is not available, it falls back on JSON::PP, and
49 then JSON::backportPP if JSON::PP is not available either.
50
51 If you always don't want it to fall back on pure perl modules, set
52 the variable like this ("export" may be "setenv", "set" and the
53 likes, depending on your environment):
54
55 > export PERL_JSON_BACKEND=JSON::XS
56
57 If you prefer Cpanel::JSON::XS to JSON::XS, then:
58
59 > export PERL_JSON_BACKEND=Cpanel::JSON::XS,JSON::XS,JSON::PP
60
61 You may also want to set this variable at the top of your test
62 files, in order not to be bothered with incompatibilities between
63 backends (you need to wrap this in "BEGIN", and set before
64 actually "use"-ing JSON module, as it decides its backend as soon
65 as it's loaded):
66
67 BEGIN { $ENV{PERL_JSON_BACKEND}='JSON::backportPP'; }
68 use JSON;
69
70USING OPTIONAL FEATURES
71 There are a few options you can set when you "use" this module:
72
73 -support_by_pp
74 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
75
76 use JSON -support_by_pp;
77
78 my $json = JSON->new;
79 # escape_slash is for JSON::PP only.
80 $json->allow_nonref->escape_slash->encode("/");
81
82 With this option, this module loads its pure perl backend
83 along with its XS backend (if available), and lets the XS
84 backend to watch if you set a flag only JSON::PP supports.
85 When you do, the internal JSON::XS object is replaced with a
86 newly created JSON::PP object with the setting copied from the
87 XS object, so that you can use JSON::PP flags (and its slower
88 "decode"/"encode" methods) from then on. In other words, this
89 is not something that allows you to hook JSON::XS to change
90 its behavior while keeping its speed. JSON::XS and JSON::PP
91 objects are quite different (JSON::XS object is a blessed
92 scalar reference, while JSON::PP object is a blessed hash
93 reference), and can't share their internals.
94
95 To avoid needless overhead (by copying settings), you are
96 advised not to use this option and just to use JSON::PP
97 explicitly when you need JSON::PP features.
98
99 -convert_blessed_universally
100 use JSON -convert_blessed_universally;
101
102 my $json = JSON->new->allow_nonref->convert_blessed;
103 my $object = bless {foo => 'bar'}, 'Foo';
104 $json->encode($object); # => {"foo":"bar"}
105
106 JSON::XS-compatible backend modules don't encode blessed
107 objects by default (except for their boolean values, which are
108 typically blessed JSON::PP::Boolean objects). If you need to
109 encode a data structure that may contain objects, you usually
110 need to look into the structure and replace objects with
111 alternative non-blessed values, or enable "convert_blessed"
112 and provide a "TO_JSON" method for each object's (base) class
113 that may be found in the structure, in order to let the
114 methods replace the objects with whatever scalar values the
115 methods return.
116
117 If you need to serialise data structures that may contain
118 arbitrary objects, it's probably better to use other
119 serialisers (such as Sereal or Storable for example), but if
120 you do want to use this module for that purpose,
121 "-convert_blessed_universally" option may help, which tweaks
122 "encode" method of the backend to install "UNIVERSAL::TO_JSON"
123 method (locally) before encoding, so that all the objects that
124 don't have their own "TO_JSON" method can fall back on the
125 method in the "UNIVERSAL" namespace. Note that you still need
126 to enable "convert_blessed" flag to actually encode objects in
127 a data structure, and "UNIVERSAL::TO_JSON" method installed by
128 this option only converts blessed hash/array references into
129 their unblessed clone (including private keys/values that are
130 not supposed to be exposed). Other blessed references will be
131 converted into null.
132
133 This feature is experimental and may be removed in the future.
134
135 -no_export
136 When you don't want to import functional interfaces from a
137 module, you usually supply "()" to its "use" statement.
138
139 use JSON (); # no functional interfaces
140
141 If you don't want to import functional interfaces, but you
142 also want to use any of the above options, add "-no_export" to
143 the option list.
144
145 # no functional interfaces, while JSON::PP support is enabled.
146 use JSON -support_by_pp, -no_export;
147
148FUNCTIONAL INTERFACE
149 This section is taken from JSON::XS. "encode_json" and
150 "decode_json" are exported by default.
151
152 This module also exports "to_json" and "from_json" for backward
153 compatibility. These are slower, and may expect/generate different
154 stuff from what "encode_json" and "decode_json" do, depending on
155 their options. It's better just to use Object-Oriented interfaces
156 than using these two functions.
157
158 encode_json
159 $json_text = encode_json $perl_scalar
160
161 Converts the given Perl data structure to a UTF-8 encoded, binary
162 string (that is, the string contains octets only). Croaks on
163 error.
164
165 This function call is functionally identical to:
166
167 $json_text = JSON->new->utf8->encode($perl_scalar)
168
169 Except being faster.
170
171 decode_json
172 $perl_scalar = decode_json $json_text
173
174 The opposite of "encode_json": expects an UTF-8 (binary) string
175 and tries to parse that as an UTF-8 encoded JSON text, returning
176 the resulting reference. Croaks on error.
177
178 This function call is functionally identical to:
179
180 $perl_scalar = JSON->new->utf8->decode($json_text)
181
182 Except being faster.
183
184 to_json
185 $json_text = to_json($perl_scalar[, $optional_hashref])
186
187 Converts the given Perl data structure to a Unicode string by
188 default. Croaks on error.
189
190 Basically, this function call is functionally identical to:
191
192 $json_text = JSON->new->encode($perl_scalar)
193
194 Except being slower.
195
196 You can pass an optional hash reference to modify its behavior,
197 but that may change what "to_json" expects/generates (see
198 "ENCODING/CODESET FLAG NOTES" for details).
199
200 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
201 # => JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
202
203 from_json
204 $perl_scalar = from_json($json_text[, $optional_hashref])
205
206 The opposite of "to_json": expects a Unicode string and tries to
207 parse it, returning the resulting reference. Croaks on error.
208
209 Basically, this function call is functionally identical to:
210
211 $perl_scalar = JSON->new->decode($json_text)
212
213 You can pass an optional hash reference to modify its behavior,
214 but that may change what "from_json" expects/generates (see
215 "ENCODING/CODESET FLAG NOTES" for details).
216
217 $perl_scalar = from_json($json_text, {utf8 => 1})
218 # => JSON->new->utf8(1)->decode($json_text)
219
220 JSON::is_bool
221 $is_boolean = JSON::is_bool($scalar)
222
223 Returns true if the passed scalar represents either JSON::true or
224 JSON::false, two constants that act like 1 and 0 respectively and
225 are also used to represent JSON "true" and "false" in Perl
226 strings.
227
228 See MAPPING, below, for more information on how JSON values are
229 mapped to Perl.
230
231COMMON OBJECT-ORIENTED INTERFACE
232 This section is also taken from JSON::XS.
233
234 The object oriented interface lets you configure your own encoding
235 or decoding style, within the limits of supported formats.
236
237 new
238 $json = JSON->new
239
240 Creates a new JSON::XS-compatible backend object that can be used
241 to de/encode JSON strings. All boolean flags described below are
242 by default *disabled*.
243
244 The mutators for flags all return the backend object again and
245 thus calls can be chained:
246
247 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
248 => {"a": [1, 2]}
249
250 ascii
251 $json = $json->ascii([$enable])
252
253 $enabled = $json->get_ascii
254
255 If $enable is true (or missing), then the "encode" method will not
256 generate characters outside the code range 0..127 (which is
257 ASCII). Any Unicode characters outside that range will be escaped
258 using either a single \uXXXX (BMP characters) or a double
259 \uHHHH\uLLLLL escape sequence, as per RFC4627. The resulting
260 encoded JSON text can be treated as a native Unicode string, an
261 ascii-encoded, latin1-encoded or UTF-8 encoded string, or any
262 other superset of ASCII.
263
264 If $enable is false, then the "encode" method will not escape
265 Unicode characters unless required by the JSON syntax or other
266 flags. This results in a faster and more compact format.
267
268 See also the section *ENCODING/CODESET FLAG NOTES* later in this
269 document.
270
271 The main use for this flag is to produce JSON texts that can be
272 transmitted over a 7-bit channel, as the encoded JSON texts will
273 not contain any 8 bit characters.
274
275 JSON->new->ascii(1)->encode([chr 0x10401])
276 => ["\ud801\udc01"]
277
278 latin1
279 $json = $json->latin1([$enable])
280
281 $enabled = $json->get_latin1
282
283 If $enable is true (or missing), then the "encode" method will
284 encode the resulting JSON text as latin1 (or iso-8859-1), escaping
285 any characters outside the code range 0..255. The resulting string
286 can be treated as a latin1-encoded JSON text or a native Unicode
287 string. The "decode" method will not be affected in any way by
288 this flag, as "decode" by default expects Unicode, which is a
289 strict superset of latin1.
290
291 If $enable is false, then the "encode" method will not escape
292 Unicode characters unless required by the JSON syntax or other
293 flags.
294
295 See also the section *ENCODING/CODESET FLAG NOTES* later in this
296 document.
297
298 The main use for this flag is efficiently encoding binary data as
299 JSON text, as most octets will not be escaped, resulting in a
300 smaller encoded size. The disadvantage is that the resulting JSON
301 text is encoded in latin1 (and must correctly be treated as such
302 when storing and transferring), a rare encoding for JSON. It is
303 therefore most useful when you want to store data structures known
304 to contain binary data efficiently in files or databases, not when
305 talking to other JSON encoders/decoders.
306
307 JSON->new->latin1->encode (["\x{89}\x{abc}"]
308 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
309
310 utf8
311 $json = $json->utf8([$enable])
312
313 $enabled = $json->get_utf8
314
315 If $enable is true (or missing), then the "encode" method will
316 encode the JSON result into UTF-8, as required by many protocols,
317 while the "decode" method expects to be handled an UTF-8-encoded
318 string. Please note that UTF-8-encoded strings do not contain any
319 characters outside the range 0..255, they are thus useful for
320 bytewise/binary I/O. In future versions, enabling this option
321 might enable autodetection of the UTF-16 and UTF-32 encoding
322 families, as described in RFC4627.
323
324 If $enable is false, then the "encode" method will return the JSON
325 string as a (non-encoded) Unicode string, while "decode" expects
326 thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or
327 UTF-16) needs to be done yourself, e.g. using the Encode module.
328
329 See also the section *ENCODING/CODESET FLAG NOTES* later in this
330 document.
331
332 Example, output UTF-16BE-encoded JSON:
333
334 use Encode;
335 $jsontext = encode "UTF-16BE", JSON->new->encode ($object);
336
337 Example, decode UTF-32LE-encoded JSON:
338
339 use Encode;
340 $object = JSON->new->decode (decode "UTF-32LE", $jsontext);
341
342 pretty
343 $json = $json->pretty([$enable])
344
345 This enables (or disables) all of the "indent", "space_before" and
346 "space_after" (and in the future possibly more) flags in one call
347 to generate the most readable (or most compact) form possible.
348
349 indent
350 $json = $json->indent([$enable])
351
352 $enabled = $json->get_indent
353
354 If $enable is true (or missing), then the "encode" method will use
355 a multiline format as output, putting every array member or
356 object/hash key-value pair into its own line, indenting them
357 properly.
358
359 If $enable is false, no newlines or indenting will be produced,
360 and the resulting JSON text is guaranteed not to contain any
361 "newlines".
362
363 This setting has no effect when decoding JSON texts.
364
365 space_before
366 $json = $json->space_before([$enable])
367
368 $enabled = $json->get_space_before
369
370 If $enable is true (or missing), then the "encode" method will add
371 an extra optional space before the ":" separating keys from values
372 in JSON objects.
373
374 If $enable is false, then the "encode" method will not add any
375 extra space at those places.
376
377 This setting has no effect when decoding JSON texts. You will also
378 most likely combine this setting with "space_after".
379
380 Example, space_before enabled, space_after and indent disabled:
381
382 {"key" :"value"}
383
384 space_after
385 $json = $json->space_after([$enable])
386
387 $enabled = $json->get_space_after
388
389 If $enable is true (or missing), then the "encode" method will add
390 an extra optional space after the ":" separating keys from values
391 in JSON objects and extra whitespace after the "," separating
392 key-value pairs and array members.
393
394 If $enable is false, then the "encode" method will not add any
395 extra space at those places.
396
397 This setting has no effect when decoding JSON texts.
398
399 Example, space_before and indent disabled, space_after enabled:
400
401 {"key": "value"}
402
403 relaxed
404 $json = $json->relaxed([$enable])
405
406 $enabled = $json->get_relaxed
407
408 If $enable is true (or missing), then "decode" will accept some
409 extensions to normal JSON syntax (see below). "encode" will not be
410 affected in anyway. *Be aware that this option makes you accept
411 invalid JSON texts as if they were valid!*. I suggest only to use
412 this option to parse application-specific files written by humans
413 (configuration files, resource files etc.)
414
415 If $enable is false (the default), then "decode" will only accept
416 valid JSON texts.
417
418 Currently accepted extensions are:
419
420 * list items can have an end-comma
421
422 JSON *separates* array elements and key-value pairs with
423 commas. This can be annoying if you write JSON texts manually
424 and want to be able to quickly append elements, so this
425 extension accepts comma at the end of such items not just
426 between them:
427
428 [
429 1,
430 2, <- this comma not normally allowed
431 ]
432 {
433 "k1": "v1",
434 "k2": "v2", <- this comma not normally allowed
435 }
436
437 * shell-style '#'-comments
438
439 Whenever JSON allows whitespace, shell-style comments are
440 additionally allowed. They are terminated by the first
441 carriage-return or line-feed character, after which more
442 white-space and comments are allowed.
443
444 [
445 1, # this comment not allowed in JSON
446 # neither this one...
447 ]
448
449 canonical
450 $json = $json->canonical([$enable])
451
452 $enabled = $json->get_canonical
453
454 If $enable is true (or missing), then the "encode" method will
455 output JSON objects by sorting their keys. This is adding a
456 comparatively high overhead.
457
458 If $enable is false, then the "encode" method will output
459 key-value pairs in the order Perl stores them (which will likely
460 change between runs of the same script, and can change even within
461 the same run from 5.18 onwards).
462
463 This option is useful if you want the same data structure to be
464 encoded as the same JSON text (given the same overall settings).
465 If it is disabled, the same hash might be encoded differently even
466 if contains the same data, as key-value pairs have no inherent
467 ordering in Perl.
468
469 This setting has no effect when decoding JSON texts.
470
471 This setting has currently no effect on tied hashes.
472
473 allow_nonref
474 $json = $json->allow_nonref([$enable])
475
476 $enabled = $json->get_allow_nonref
477
478 If $enable is true (or missing), then the "encode" method can
479 convert a non-reference into its corresponding string, number or
480 null JSON value, which is an extension to RFC4627. Likewise,
481 "decode" will accept those JSON values instead of croaking.
482
483 If $enable is false, then the "encode" method will croak if it
484 isn't passed an arrayref or hashref, as JSON texts must either be
485 an object or array. Likewise, "decode" will croak if given
486 something that is not a JSON object or array.
487
488 Example, encode a Perl scalar as JSON value with enabled
489 "allow_nonref", resulting in an invalid JSON text:
490
491 JSON->new->allow_nonref->encode ("Hello, World!")
492 => "Hello, World!"
493
494 allow_unknown
495 $json = $json->allow_unknown ([$enable])
496
497 $enabled = $json->get_allow_unknown
498
499 If $enable is true (or missing), then "encode" will *not* throw an
500 exception when it encounters values it cannot represent in JSON
501 (for example, filehandles) but instead will encode a JSON "null"
502 value. Note that blessed objects are not included here and are
503 handled separately by c<allow_nonref>.
504
505 If $enable is false (the default), then "encode" will throw an
506 exception when it encounters anything it cannot encode as JSON.
507
508 This option does not affect "decode" in any way, and it is
509 recommended to leave it off unless you know your communications
510 partner.
511
512 allow_blessed
513 $json = $json->allow_blessed([$enable])
514
515 $enabled = $json->get_allow_blessed
516
517 See "OBJECT SERIALISATION" for details.
518
519 If $enable is true (or missing), then the "encode" method will not
520 barf when it encounters a blessed reference that it cannot convert
521 otherwise. Instead, a JSON "null" value is encoded instead of the
522 object.
523
524 If $enable is false (the default), then "encode" will throw an
525 exception when it encounters a blessed object that it cannot
526 convert otherwise.
527
528 This setting has no effect on "decode".
529
530 convert_blessed
531 $json = $json->convert_blessed([$enable])
532
533 $enabled = $json->get_convert_blessed
534
535 See "OBJECT SERIALISATION" for details.
536
537 If $enable is true (or missing), then "encode", upon encountering
538 a blessed object, will check for the availability of the "TO_JSON"
539 method on the object's class. If found, it will be called in
540 scalar context and the resulting scalar will be encoded instead of
541 the object.
542
543 The "TO_JSON" method may safely call die if it wants. If "TO_JSON"
544 returns other blessed objects, those will be handled in the same
545 way. "TO_JSON" must take care of not causing an endless recursion
546 cycle (== crash) in this case. The name of "TO_JSON" was chosen
547 because other methods called by the Perl core (== not by the user
548 of the object) are usually in upper case letters and to avoid
549 collisions with any "to_json" function or method.
550
551 If $enable is false (the default), then "encode" will not consider
552 this type of conversion.
553
554 This setting has no effect on "decode".
555
556 filter_json_object
557 $json = $json->filter_json_object([$coderef])
558
559 When $coderef is specified, it will be called from "decode" each
560 time it decodes a JSON object. The only argument is a reference to
561 the newly-created hash. If the code references returns a single
562 scalar (which need not be a reference), this value (i.e. a copy of
563 that scalar to avoid aliasing) is inserted into the deserialised
564 data structure. If it returns an empty list (NOTE: *not* "undef",
565 which is a valid scalar), the original deserialised hash will be
566 inserted. This setting can slow down decoding considerably.
567
568 When $coderef is omitted or undefined, any existing callback will
569 be removed and "decode" will not change the deserialised hash in
570 any way.
571
572 Example, convert all JSON objects into the integer 5:
573
574 my $js = JSON->new->filter_json_object (sub { 5 });
575 # returns [5]
576 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
577 # throw an exception because allow_nonref is not enabled
578 # so a lone 5 is not allowed.
579 $js->decode ('{"a":1, "b":2}');
580
581 filter_json_single_key_object
582 $json = $json->filter_json_single_key_object($key [=> $coderef])
583
584 Works remotely similar to "filter_json_object", but is only called
585 for JSON objects having a single key named $key.
586
587 This $coderef is called before the one specified via
588 "filter_json_object", if any. It gets passed the single value in
589 the JSON object. If it returns a single value, it will be inserted
590 into the data structure. If it returns nothing (not even "undef"
591 but the empty list), the callback from "filter_json_object" will
592 be called next, as if no single-key callback were specified.
593
594 If $coderef is omitted or undefined, the corresponding callback
595 will be disabled. There can only ever be one callback for a given
596 key.
597
598 As this callback gets called less often then the
599 "filter_json_object" one, decoding speed will not usually suffer
600 as much. Therefore, single-key objects make excellent targets to
601 serialise Perl objects into, especially as single-key JSON objects
602 are as close to the type-tagged value concept as JSON gets (it's
603 basically an ID/VALUE tuple). Of course, JSON does not support
604 this in any way, so you need to make sure your data never looks
605 like a serialised Perl hash.
606
607 Typical names for the single object key are "__class_whatever__",
608 or "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or
609 even things like "__class_md5sum(classname)__", to reduce the risk
610 of clashing with real hashes.
611
612 Example, decode JSON objects of the form "{ "__widget__" => <id>
613 }" into the corresponding $WIDGET{<id>} object:
614
615 # return whatever is in $WIDGET{5}:
616 JSON
617 ->new
618 ->filter_json_single_key_object (__widget__ => sub {
619 $WIDGET{ $_[0] }
620 })
621 ->decode ('{"__widget__": 5')
622
623 # this can be used with a TO_JSON method in some "widget" class
624 # for serialisation to json:
625 sub WidgetBase::TO_JSON {
626 my ($self) = @_;
627
628 unless ($self->{id}) {
629 $self->{id} = ..get..some..id..;
630 $WIDGET{$self->{id}} = $self;
631 }
632
633 { __widget__ => $self->{id} }
634 }
635
636 max_depth
637 $json = $json->max_depth([$maximum_nesting_depth])
638
639 $max_depth = $json->get_max_depth
640
641 Sets the maximum nesting level (default 512) accepted while
642 encoding or decoding. If a higher nesting level is detected in
643 JSON text or a Perl data structure, then the encoder and decoder
644 will stop and croak at that point.
645
646 Nesting level is defined by number of hash- or arrayrefs that the
647 encoder needs to traverse to reach a given point or the number of
648 "{" or "[" characters without their matching closing parenthesis
649 crossed to reach a given character in a string.
650
651 Setting the maximum depth to one disallows any nesting, so that
652 ensures that the object is only a single hash/object or array.
653
654 If no argument is given, the highest possible setting will be
655 used, which is rarely useful.
656
657 max_size
658 $json = $json->max_size([$maximum_string_size])
659
660 $max_size = $json->get_max_size
661
662 Set the maximum length a JSON text may have (in bytes) where
663 decoding is being attempted. The default is 0, meaning no limit.
664 When "decode" is called on a string that is longer then this many
665 bytes, it will not attempt to decode the string but throw an
666 exception. This setting has no effect on "encode" (yet).
667
668 If no argument is given, the limit check will be deactivated (same
669 as when 0 is specified).
670
671 encode
672 $json_text = $json->encode($perl_scalar)
673
674 Converts the given Perl value or data structure to its JSON
675 representation. Croaks on error.
676
677 decode
678 $perl_scalar = $json->decode($json_text)
679
680 The opposite of "encode": expects a JSON text and tries to parse
681 it, returning the resulting simple scalar or reference. Croaks on
682 error.
683
684 decode_prefix
685 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
686
687 This works like the "decode" method, but instead of raising an
688 exception when there is trailing garbage after the first JSON
689 object, it will silently stop parsing there and return the number
690 of characters consumed so far.
691
692 This is useful if your JSON texts are not delimited by an outer
693 protocol and you need to know where the JSON text ends.
694
695 JSON->new->decode_prefix ("[1] the tail")
696 => ([1], 3)
697
698ADDITIONAL METHODS
699 The following methods are for this module only.
700
701 backend
702 $backend = $json->backend
703
704 Since 2.92, "backend" method returns an abstract backend module
705 used currently, which should be JSON::Backend::XS (which inherits
706 JSON::XS or Cpanel::JSON::XS), or JSON::Backend::PP (which
707 inherits JSON::PP), not to monkey-patch the actual backend module
708 globally.
709
710 If you need to know what is used actually, use "isa", instead of
711 string comparison.
712
713 is_xs
714 $boolean = $json->is_xs
715
716 Returns true if the backend inherits JSON::XS or Cpanel::JSON::XS.
717
718 is_pp
719 $boolean = $json->is_pp
720
721 Returns true if the backend inherits JSON::PP.
722
723 property
724 $settings = $json->property()
725
726 Returns a reference to a hash that holds all the common flag
727 settings.
728
729 $json = $json->property('utf8' => 1)
730 $value = $json->property('utf8') # 1
731
732 You can use this to get/set a value of a particular flag.
733
734INCREMENTAL PARSING
735 This section is also taken from JSON::XS.
736
737 In some cases, there is the need for incremental parsing of JSON
738 texts. While this module always has to keep both JSON text and
739 resulting Perl data structure in memory at one time, it does allow
740 you to parse a JSON stream incrementally. It does so by
741 accumulating text until it has a full JSON object, which it then
742 can decode. This process is similar to using "decode_prefix" to
743 see if a full JSON object is available, but is much more efficient
744 (and can be implemented with a minimum of method calls).
745
746 This module will only attempt to parse the JSON text once it is
747 sure it has enough text to get a decisive result, using a very
748 simple but truly incremental parser. This means that it sometimes
749 won't stop as early as the full parser, for example, it doesn't
750 detect mismatched parentheses. The only thing it guarantees is
751 that it starts decoding as soon as a syntactically valid JSON text
752 has been seen. This means you need to set resource limits (e.g.
753 "max_size") to ensure the parser will stop parsing in the presence
754 if syntax errors.
755
756 The following methods implement this incremental parser.
757
758 incr_parse
759 $json->incr_parse( [$string] ) # void context
760
761 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
762
763 @obj_or_empty = $json->incr_parse( [$string] ) # list context
764
765 This is the central parsing function. It can both append new text
766 and extract objects from the stream accumulated so far (both of
767 these functions are optional).
768
769 If $string is given, then this string is appended to the already
770 existing JSON fragment stored in the $json object.
771
772 After that, if the function is called in void context, it will
773 simply return without doing anything further. This can be used to
774 add more text in as many chunks as you want.
775
776 If the method is called in scalar context, then it will try to
777 extract exactly *one* JSON object. If that is successful, it will
778 return this object, otherwise it will return "undef". If there is
779 a parse error, this method will croak just as "decode" would do
780 (one can then use "incr_skip" to skip the erroneous part). This is
781 the most common way of using the method.
782
783 And finally, in list context, it will try to extract as many
784 objects from the stream as it can find and return them, or the
785 empty list otherwise. For this to work, there must be no
786 separators (other than whitespace) between the JSON objects or
787 arrays, instead they must be concatenated back-to-back. If an
788 error occurs, an exception will be raised as in the scalar context
789 case. Note that in this case, any previously-parsed JSON texts
790 will be lost.
791
792 Example: Parse some JSON arrays/objects in a given string and
793 return them.
794
795 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
796
797 incr_text
798 $lvalue_string = $json->incr_text
799
800 This method returns the currently stored JSON fragment as an
801 lvalue, that is, you can manipulate it. This *only* works when a
802 preceding call to "incr_parse" in *scalar context* successfully
803 returned an object. Under all other circumstances you must not
804 call this function (I mean it. although in simple tests it might
805 actually work, it *will* fail under real world conditions). As a
806 special exception, you can also call this method before having
807 parsed anything.
808
809 That means you can only use this function to look at or manipulate
810 text before or after complete JSON objects, not while the parser
811 is in the middle of parsing a JSON object.
812
813 This function is useful in two cases: a) finding the trailing text
814 after a JSON object or b) parsing multiple JSON objects separated
815 by non-JSON text (such as commas).
816
817 incr_skip
818 $json->incr_skip
819
820 This will reset the state of the incremental parser and will
821 remove the parsed text from the input buffer so far. This is
822 useful after "incr_parse" died, in which case the input buffer and
823 incremental parser state is left unchanged, to skip the text
824 parsed so far and to reset the parse state.
825
826 The difference to "incr_reset" is that only text until the parse
827 error occurred is removed.
828
829 incr_reset
830 $json->incr_reset
831
832 This completely resets the incremental parser, that is, after this
833 call, it will be as if the parser had never parsed anything.
834
835 This is useful if you want to repeatedly parse JSON objects and
836 want to ignore any trailing data, which means you have to reset
837 the parser after each successful decode.
838
839MAPPING
840 Most of this section is also taken from JSON::XS.
841
842 This section describes how the backend modules map Perl values to
843 JSON values and vice versa. These mappings are designed to "do the
844 right thing" in most circumstances automatically, preserving
845 round-tripping characteristics (what you put in comes out as
846 something equivalent).
847
848 For the more enlightened: note that in the following descriptions,
849 lowercase *perl* refers to the Perl interpreter, while uppercase
850 *Perl* refers to the abstract Perl language itself.
851
852 JSON -> PERL
853 object
854 A JSON object becomes a reference to a hash in Perl. No
855 ordering of object keys is preserved (JSON does not preserver
856 object key ordering itself).
857
858 array
859 A JSON array becomes a reference to an array in Perl.
860
861 string
862 A JSON string becomes a string scalar in Perl - Unicode
863 codepoints in JSON are represented by the same codepoints in
864 the Perl string, so no manual decoding is necessary.
865
866 number
867 A JSON number becomes either an integer, numeric (floating
868 point) or string scalar in perl, depending on its range and
869 any fractional parts. On the Perl level, there is no
870 difference between those as Perl handles all the conversion
871 details, but an integer may take slightly less memory and
872 might represent more values exactly than floating point
873 numbers.
874
875 If the number consists of digits only, this module will try to
876 represent it as an integer value. If that fails, it will try
877 to represent it as a numeric (floating point) value if that is
878 possible without loss of precision. Otherwise it will preserve
879 the number as a string value (in which case you lose
880 roundtripping ability, as the JSON number will be re-encoded
881 to a JSON string).
882
883 Numbers containing a fractional or exponential part will
884 always be represented as numeric (floating point) values,
885 possibly at a loss of precision (in which case you might lose
886 perfect roundtripping ability, but the JSON number will still
887 be re-encoded as a JSON number).
888
889 Note that precision is not accuracy - binary floating point
890 values cannot represent most decimal fractions exactly, and
891 when converting from and to floating point, this module only
892 guarantees precision up to but not including the least
893 significant bit.
894
895 true, false
896 These JSON atoms become "JSON::true" and "JSON::false",
897 respectively. They are overloaded to act almost exactly like
898 the numbers 1 and 0. You can check whether a scalar is a JSON
899 boolean by using the "JSON::is_bool" function.
900
901 null
902 A JSON null atom becomes "undef" in Perl.
903
904 shell-style comments ("# *text*")
905 As a nonstandard extension to the JSON syntax that is enabled
906 by the "relaxed" setting, shell-style comments are allowed.
907 They can start anywhere outside strings and go till the end of
908 the line.
909
910 PERL -> JSON
911 The mapping from Perl to JSON is slightly more difficult, as Perl
912 is a truly typeless language, so we can only guess which JSON type
913 is meant by a Perl value.
914
915 hash references
916 Perl hash references become JSON objects. As there is no
917 inherent ordering in hash keys (or JSON objects), they will
918 usually be encoded in a pseudo-random order. This module can
919 optionally sort the hash keys (determined by the *canonical*
920 flag), so the same data structure will serialise to the same
921 JSON text (given same settings and version of the same
922 backend), but this incurs a runtime overhead and is only
923 rarely useful, e.g. when you want to compare some JSON text
924 against another for equality.
925
926 array references
927 Perl array references become JSON arrays.
928
929 other references
930 Other unblessed references are generally not allowed and will
931 cause an exception to be thrown, except for references to the
932 integers 0 and 1, which get turned into "false" and "true"
933 atoms in JSON. You can also use "JSON::false" and "JSON::true"
934 to improve readability.
935
936 encode_json [\0,JSON::true] # yields [false,true]
937
938 JSON::true, JSON::false, JSON::null
939 These special values become JSON true and JSON false values,
940 respectively. You can also use "\1" and "\0" directly if you
941 want.
942
943 blessed objects
944 Blessed objects are not directly representable in JSON, but
945 "JSON::XS" allows various ways of handling objects. See
946 "OBJECT SERIALISATION", below, for details.
947
948 simple scalars
949 Simple Perl scalars (any scalar that is not a reference) are
950 the most difficult objects to encode: this module will encode
951 undefined scalars as JSON "null" values, scalars that have
952 last been used in a string context before encoding as JSON
953 strings, and anything else as number value:
954
955 # dump as number
956 encode_json [2] # yields [2]
957 encode_json [-3.0e17] # yields [-3e+17]
958 my $value = 5; encode_json [$value] # yields [5]
959
960 # used as string, so dump as string
961 print $value;
962 encode_json [$value] # yields ["5"]
963
964 # undef becomes null
965 encode_json [undef] # yields [null]
966
967 You can force the type to be a string by stringifying it:
968
969 my $x = 3.1; # some variable containing a number
970 "$x"; # stringified
971 $x .= ""; # another, more awkward way to stringify
972 print $x; # perl does it for you, too, quite often
973
974 You can force the type to be a number by numifying it:
975
976 my $x = "3"; # some variable containing a string
977 $x += 0; # numify it, ensuring it will be dumped as a number
978 $x *= 1; # same thing, the choice is yours.
979
980 You can not currently force the type in other, less obscure,
981 ways. Tell me if you need this capability (but don't forget to
982 explain why it's needed :).
983
984 Note that numerical precision has the same meaning as under
985 Perl (so binary to decimal conversion follows the same rules
986 as in Perl, which can differ to other languages). Also, your
987 perl interpreter might expose extensions to the floating point
988 numbers of your platform, such as infinities or NaN's - these
989 cannot be represented in JSON, and it is an error to pass
990 those in.
991
992 OBJECT SERIALISATION
993 As for Perl objects, this module only supports a pure JSON
994 representation (without the ability to deserialise the object
995 automatically again).
996
997 SERIALISATION
998 What happens when this module encounters a Perl object depends on
999 the "allow_blessed" and "convert_blessed" settings, which are used
1000 in this order:
1001
1002 1. "convert_blessed" is enabled and the object has a "TO_JSON"
1003 method.
1004 In this case, the "TO_JSON" method of the object is invoked in
1005 scalar context. It must return a single scalar that can be
1006 directly encoded into JSON. This scalar replaces the object in
1007 the JSON text.
1008
1009 For example, the following "TO_JSON" method will convert all
1010 URI objects to JSON strings when serialised. The fact that
1011 these values originally were URI objects is lost.
1012
1013 sub URI::TO_JSON {
1014 my ($uri) = @_;
1015 $uri->as_string
1016 }
1017
1018 2. "allow_blessed" is enabled.
1019 The object will be serialised as a JSON null value.
1020
1021 3. none of the above
1022 If none of the settings are enabled or the respective methods
1023 are missing, this module throws an exception.
1024
1025ENCODING/CODESET FLAG NOTES
1026 This section is taken from JSON::XS.
1027
1028 The interested reader might have seen a number of flags that
1029 signify encodings or codesets - "utf8", "latin1" and "ascii".
1030 There seems to be some confusion on what these do, so here is a
1031 short comparison:
1032
1033 "utf8" controls whether the JSON text created by "encode" (and
1034 expected by "decode") is UTF-8 encoded or not, while "latin1" and
1035 "ascii" only control whether "encode" escapes character values
1036 outside their respective codeset range. Neither of these flags
1037 conflict with each other, although some combinations make less
1038 sense than others.
1039
1040 Care has been taken to make all flags symmetrical with respect to
1041 "encode" and "decode", that is, texts encoded with any combination
1042 of these flag values will be correctly decoded when the same flags
1043 are used - in general, if you use different flag settings while
1044 encoding vs. when decoding you likely have a bug somewhere.
1045
1046 Below comes a verbose discussion of these flags. Note that a
1047 "codeset" is simply an abstract set of character-codepoint pairs,
1048 while an encoding takes those codepoint numbers and *encodes*
1049 them, in our case into octets. Unicode is (among other things) a
1050 codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and
1051 ASCII are both codesets *and* encodings at the same time, which
1052 can be confusing.
1053
1054 "utf8" flag disabled
1055 When "utf8" is disabled (the default), then "encode"/"decode"
1056 generate and expect Unicode strings, that is, characters with
1057 high ordinal Unicode values (> 255) will be encoded as such
1058 characters, and likewise such characters are decoded as-is, no
1059 changes to them will be done, except "(re-)interpreting" them
1060 as Unicode codepoints or Unicode characters, respectively (to
1061 Perl, these are the same thing in strings unless you do
1062 funny/weird/dumb stuff).
1063
1064 This is useful when you want to do the encoding yourself (e.g.
1065 when you want to have UTF-16 encoded JSON texts) or when some
1066 other layer does the encoding for you (for example, when
1067 printing to a terminal using a filehandle that transparently
1068 encodes to UTF-8 you certainly do NOT want to UTF-8 encode
1069 your data first and have Perl encode it another time).
1070
1071 "utf8" flag enabled
1072 If the "utf8"-flag is enabled, "encode"/"decode" will encode
1073 all characters using the corresponding UTF-8 multi-byte
1074 sequence, and will expect your input strings to be encoded as
1075 UTF-8, that is, no "character" of the input string must have
1076 any value > 255, as UTF-8 does not allow that.
1077
1078 The "utf8" flag therefore switches between two modes: disabled
1079 means you will get a Unicode string in Perl, enabled means you
1080 get an UTF-8 encoded octet/binary string in Perl.
1081
1082 "latin1" or "ascii" flags enabled
1083 With "latin1" (or "ascii") enabled, "encode" will escape
1084 characters with ordinal values > 255 (> 127 with "ascii") and
1085 encode the remaining characters as specified by the "utf8"
1086 flag.
1087
1088 If "utf8" is disabled, then the result is also correctly
1089 encoded in those character sets (as both are proper subsets of
1090 Unicode, meaning that a Unicode string with all character
1091 values < 256 is the same thing as a ISO-8859-1 string, and a
1092 Unicode string with all character values < 128 is the same
1093 thing as an ASCII string in Perl).
1094
1095 If "utf8" is enabled, you still get a correct UTF-8-encoded
1096 string, regardless of these flags, just some more characters
1097 will be escaped using "\uXXXX" then before.
1098
1099 Note that ISO-8859-1-*encoded* strings are not compatible with
1100 UTF-8 encoding, while ASCII-encoded strings are. That is
1101 because the ISO-8859-1 encoding is NOT a subset of UTF-8
1102 (despite the ISO-8859-1 *codeset* being a subset of Unicode),
1103 while ASCII is.
1104
1105 Surprisingly, "decode" will ignore these flags and so treat
1106 all input values as governed by the "utf8" flag. If it is
1107 disabled, this allows you to decode ISO-8859-1- and
1108 ASCII-encoded strings, as both strict subsets of Unicode. If
1109 it is enabled, you can correctly decode UTF-8 encoded strings.
1110
1111 So neither "latin1" nor "ascii" are incompatible with the
1112 "utf8" flag - they only govern when the JSON output engine
1113 escapes a character or not.
1114
1115 The main use for "latin1" is to relatively efficiently store
1116 binary data as JSON, at the expense of breaking compatibility
1117 with most JSON decoders.
1118
1119 The main use for "ascii" is to force the output to not contain
1120 characters with values > 127, which means you can interpret
1121 the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or
1122 most about any character set and 8-bit-encoding, and still get
1123 the same data structure back. This is useful when your channel
1124 for JSON transfer is not 8-bit clean or the encoding might be
1125 mangled in between (e.g. in mail), and works because ASCII is
1126 a proper subset of most 8-bit and multibyte encodings in use
1127 in the world.
1128
1129BACKWARD INCOMPATIBILITY
1130 Since version 2.90, stringification (and string comparison) for
1131 "JSON::true" and "JSON::false" has not been overloaded. It
1132 shouldn't matter as long as you treat them as boolean values, but
1133 a code that expects they are stringified as "true" or "false"
1134 doesn't work as you have expected any more.
1135
1136 if (JSON::true eq 'true') { # now fails
1137
1138 print "The result is $JSON::true now."; # => The result is 1 now.
1139
1140 And now these boolean values don't inherit JSON::Boolean, either.
1141 When you need to test a value is a JSON boolean value or not, use
1142 "JSON::is_bool" function, instead of testing the value inherits a
1143 particular boolean class or not.
1144
1145BUGS
1146 Please report bugs on backend selection and additional features
1147 this module provides to RT or GitHub issues for this module:
1148
1149 https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON
1150 https://github.com/makamaka/JSON/issues
1151
1152 Please report bugs and feature requests on decoding/encoding and
1153 boolean behaviors to the author of the backend module you are
1154 using.
1155
1156SEE ALSO
1157 JSON::XS, Cpanel::JSON::XS, JSON::PP for backends.
1158
1159 JSON::MaybeXS, an alternative that prefers Cpanel::JSON::XS.
1160
1161 "RFC4627"(<http://www.ietf.org/rfc/rfc4627.txt>)
1162
1163AUTHOR
1164 Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
1165
1166 JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
1167
1168 The release of this new version owes to the courtesy of Marc
1169 Lehmann.
1170
1171COPYRIGHT AND LICENSE
1172 Copyright 2005-2013 by Makamaka Hannyaharamitu
1173
1174 This library is free software; you can redistribute it and/or
1175 modify it under the same terms as Perl itself.
1176
1177