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