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