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