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
25 # If you want to use PP only support features, call with '-support_by_pp'
26 # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
27
28 use JSON -support_by_pp;
29
30 # option-acceptable interfaces (expect/generate UNICODE by default)
31
32 $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
33 $perl_scalar = from_json( $json_text, { utf8 => 1 } );
34
35 # Between (en|de)code_json and (to|from)_json, if you want to write
36 # a code which communicates to an outer world (encoded in UTF-8),
37 # recommend to use (en|de)code_json.
38
40 2.59
41
42 This version is compatible with JSON::XS 2.34 and later.
43
45 JSON::PP was earlier included in the "JSON" distribution, but has since
46 Perl 5.14 been a core module. For this reason, JSON::PP was removed
47 from the JSON distribution and can now be found also in the Perl5
48 repository at
49
50 · <http://perl5.git.perl.org/perl.git>
51
52 (The newest JSON::PP version still exists in CPAN.)
53
54 Instead, the "JSON" distribution will include JSON::backportPP for
55 backwards computability. JSON.pm should thus work as it did before.
56
58 ************************** CAUTION ********************************
59 * This is 'JSON module version 2' and there are many differences *
60 * to version 1.xx *
61 * Please check your applications using old version. *
62 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
63 *******************************************************************
64
65 JSON (JavaScript Object Notation) is a simple data format. See to
66 <http://www.json.org/> and
67 "RFC4627"(<http://www.ietf.org/rfc/rfc4627.txt>).
68
69 This module converts Perl data structures to JSON and vice versa using
70 either JSON::XS or JSON::PP.
71
72 JSON::XS is the fastest and most proper JSON module on CPAN which must
73 be compiled and installed in your environment. JSON::PP is a pure-Perl
74 module which is bundled in this distribution and has a strong
75 compatibility to JSON::XS.
76
77 This module try to use JSON::XS by default and fail to it, use JSON::PP
78 instead. So its features completely depend on JSON::XS or JSON::PP.
79
80 See to "BACKEND MODULE DECISION".
81
82 To distinguish the module name 'JSON' and the format type JSON, the
83 former is quoted by C<> (its results vary with your using media), and
84 the latter is left just as it is.
85
86 Module name : "JSON"
87
88 Format type : JSON
89
90 FEATURES
91 · correct unicode handling
92
93 This module (i.e. backend modules) knows how to handle Unicode,
94 documents how and when it does so, and even documents what
95 "correct" means.
96
97 Even though there are limitations, this feature is available since
98 Perl version 5.6.
99
100 JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or
101 later), so in older versions "JSON" should call JSON::PP as the
102 backend which can be used since Perl 5.005.
103
104 With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of
105 a Perl side problem, JSON::PP works slower in the versions. And in
106 5.005, the Unicode handling is not available. See to "UNICODE
107 HANDLING ON PERLS" in JSON::PP for more information.
108
109 See also to "A FEW NOTES ON UNICODE AND PERL" in JSON::XS and
110 "ENCODING/CODESET_FLAG_NOTES" in JSON::XS.
111
112 · round-trip integrity
113
114 When you serialise a perl data structure using only data types
115 supported by JSON and Perl, the deserialised data structure is
116 identical on the Perl level. (e.g. the string "2.0" doesn't
117 suddenly become "2" just because it looks like a number). There are
118 minor exceptions to this, read the "MAPPING" section below to learn
119 about those.
120
121 · strict checking of JSON correctness
122
123 There is no guessing, no generating of illegal JSON texts by
124 default, and only JSON is accepted as input by default (the latter
125 is a security feature).
126
127 See to "FEATURES" in JSON::XS and "FEATURES" in JSON::PP.
128
129 · fast
130
131 This module returns a JSON::XS object itself if available.
132 Compared to other JSON modules and other serialisers such as
133 Storable, JSON::XS usually compares favorably in terms of speed,
134 too.
135
136 If not available, "JSON" returns a JSON::PP object instead of
137 JSON::XS and it is very slow as pure-Perl.
138
139 · simple to use
140
141 This module has both a simple functional interface as well as an
142 object oriented interface interface.
143
144 · reasonably versatile output formats
145
146 You can choose between the most compact guaranteed-single-line
147 format possible (nice for simple line-based protocols), a pure-
148 ASCII format (for when your transport is not 8-bit clean, still
149 supports the whole Unicode range), or a pretty-printed format (for
150 when you want to read that stuff). Or you can combine those
151 features in whatever way you like.
152
154 Some documents are copied and modified from "FUNCTIONAL INTERFACE" in
155 JSON::XS. "to_json" and "from_json" are additional 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.
162
163 This function call is functionally identical to:
164
165 $json_text = JSON->new->utf8->encode($perl_scalar)
166
167 decode_json
168 $perl_scalar = decode_json $json_text
169
170 The opposite of "encode_json": expects an UTF-8 (binary) string and
171 tries to parse that as an UTF-8 encoded JSON text, returning the
172 resulting reference.
173
174 This function call is functionally identical to:
175
176 $perl_scalar = JSON->new->utf8->decode($json_text)
177
178 to_json
179 $json_text = to_json($perl_scalar)
180
181 Converts the given Perl data structure to a json string.
182
183 This function call is functionally identical to:
184
185 $json_text = JSON->new->encode($perl_scalar)
186
187 Takes a hash reference as the second.
188
189 $json_text = to_json($perl_scalar, $flag_hashref)
190
191 So,
192
193 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
194
195 equivalent to:
196
197 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
198
199 If you want to write a modern perl code which communicates to outer
200 world, you should use "encode_json" (supposed that JSON data are
201 encoded in UTF-8).
202
203 from_json
204 $perl_scalar = from_json($json_text)
205
206 The opposite of "to_json": expects a json string and tries to parse it,
207 returning the resulting reference.
208
209 This function call is functionally identical to:
210
211 $perl_scalar = JSON->decode($json_text)
212
213 Takes a hash reference as the second.
214
215 $perl_scalar = from_json($json_text, $flag_hashref)
216
217 So,
218
219 $perl_scalar = from_json($json_text, {utf8 => 1})
220
221 equivalent to:
222
223 $perl_scalar = JSON->new->utf8(1)->decode($json_text)
224
225 If you want to write a modern perl code which communicates to outer
226 world, you should use "decode_json" (supposed that JSON data are
227 encoded in UTF-8).
228
229 JSON::is_bool
230 $is_boolean = JSON::is_bool($scalar)
231
232 Returns true if the passed scalar represents either JSON::true or
233 JSON::false, two constants that act like 1 and 0 respectively and are
234 also used to represent JSON "true" and "false" in Perl strings.
235
236 JSON::true
237 Returns JSON true value which is blessed object. It "isa"
238 JSON::Boolean object.
239
240 JSON::false
241 Returns JSON false value which is blessed object. It "isa"
242 JSON::Boolean object.
243
244 JSON::null
245 Returns "undef".
246
247 See MAPPING, below, for more information on how JSON values are mapped
248 to Perl.
249
251 This section supposes that your perl version is 5.8 or later.
252
253 If you know a JSON text from an outer world - a network, a file
254 content, and so on, is encoded in UTF-8, you should use "decode_json"
255 or "JSON" module object with "utf8" enable. And the decoded result will
256 contain UNICODE characters.
257
258 # from network
259 my $json = JSON->new->utf8;
260 my $json_text = CGI->new->param( 'json_data' );
261 my $perl_scalar = $json->decode( $json_text );
262
263 # from file content
264 local $/;
265 open( my $fh, '<', 'json.data' );
266 $json_text = <$fh>;
267 $perl_scalar = decode_json( $json_text );
268
269 If an outer data is not encoded in UTF-8, firstly you should "decode"
270 it.
271
272 use Encode;
273 local $/;
274 open( my $fh, '<', 'json.data' );
275 my $encoding = 'cp932';
276 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
277
278 # or you can write the below code.
279 #
280 # open( my $fh, "<:encoding($encoding)", 'json.data' );
281 # $unicode_json_text = <$fh>;
282
283 In this case, $unicode_json_text is of course UNICODE string. So you
284 cannot use "decode_json" nor "JSON" module object with "utf8" enable.
285 Instead of them, you use "JSON" module object with "utf8" disable or
286 "from_json".
287
288 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
289 # or
290 $perl_scalar = from_json( $unicode_json_text );
291
292 Or "encode 'utf8'" and "decode_json":
293
294 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
295 # this way is not efficient.
296
297 And now, you want to convert your $perl_scalar into JSON data and send
298 it to an outer world - a network or a file content, and so on.
299
300 Your data usually contains UNICODE strings and you want the converted
301 data to be encoded in UTF-8, you should use "encode_json" or "JSON"
302 module object with "utf8" enable.
303
304 print encode_json( $perl_scalar ); # to a network? file? or display?
305 # or
306 print $json->utf8->encode( $perl_scalar );
307
308 If $perl_scalar does not contain UNICODE but $encoding-encoded strings
309 for some reason, then its characters are regarded as latin1 for perl
310 (because it does not concern with your $encoding). You cannot use
311 "encode_json" nor "JSON" module object with "utf8" enable. Instead of
312 them, you use "JSON" module object with "utf8" disable or "to_json".
313 Note that the resulted text is a UNICODE string but no problem to print
314 it.
315
316 # $perl_scalar contains $encoding encoded string values
317 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
318 # or
319 $unicode_json_text = to_json( $perl_scalar );
320 # $unicode_json_text consists of characters less than 0x100
321 print $unicode_json_text;
322
323 Or "decode $encoding" all string values and "encode_json":
324
325 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
326 # ... do it to each string values, then encode_json
327 $json_text = encode_json( $perl_scalar );
328
329 This method is a proper way but probably not efficient.
330
331 See to Encode, perluniintro.
332
334 new
335 $json = JSON->new
336
337 Returns a new "JSON" object inherited from either JSON::XS or JSON::PP
338 that can be used to de/encode JSON strings.
339
340 All boolean flags described below are by default disabled.
341
342 The mutators for flags all return the JSON object again and thus calls
343 can be chained:
344
345 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
346 => {"a": [1, 2]}
347
348 ascii
349 $json = $json->ascii([$enable])
350
351 $enabled = $json->get_ascii
352
353 If $enable is true (or missing), then the encode method will not
354 generate characters outside the code range 0..127. Any Unicode
355 characters outside that range will be escaped using either a single
356 \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
357
358 If $enable is false, then the encode method will not escape Unicode
359 characters unless required by the JSON syntax or other flags. This
360 results in a faster and more compact format.
361
362 This feature depends on the used Perl version and environment.
363
364 See to "UNICODE HANDLING ON PERLS" in JSON::PP if the backend is PP.
365
366 JSON->new->ascii(1)->encode([chr 0x10401])
367 => ["\ud801\udc01"]
368
369 latin1
370 $json = $json->latin1([$enable])
371
372 $enabled = $json->get_latin1
373
374 If $enable is true (or missing), then the encode method will encode the
375 resulting JSON text as latin1 (or iso-8859-1), escaping any characters
376 outside the code range 0..255.
377
378 If $enable is false, then the encode method will not escape Unicode
379 characters unless required by the JSON syntax or other flags.
380
381 JSON->new->latin1->encode (["\x{89}\x{abc}"]
382 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
383
384 utf8
385 $json = $json->utf8([$enable])
386
387 $enabled = $json->get_utf8
388
389 If $enable is true (or missing), then the encode method will encode the
390 JSON result into UTF-8, as required by many protocols, while the decode
391 method expects to be handled an UTF-8-encoded string. Please note that
392 UTF-8-encoded strings do not contain any characters outside the range
393 0..255, they are thus useful for bytewise/binary I/O.
394
395 In future versions, enabling this option might enable autodetection of
396 the UTF-16 and UTF-32 encoding families, as described in RFC4627.
397
398 If $enable is false, then the encode method will return the JSON string
399 as a (non-encoded) Unicode string, while decode expects thus a Unicode
400 string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be
401 done yourself, e.g. using the Encode module.
402
403 Example, output UTF-16BE-encoded JSON:
404
405 use Encode;
406 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
407
408 Example, decode UTF-32LE-encoded JSON:
409
410 use Encode;
411 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
412
413 See to "UNICODE HANDLING ON PERLS" in JSON::PP if the backend is PP.
414
415 pretty
416 $json = $json->pretty([$enable])
417
418 This enables (or disables) all of the "indent", "space_before" and
419 "space_after" (and in the future possibly more) flags in one call to
420 generate the most readable (or most compact) form possible.
421
422 Equivalent to:
423
424 $json->indent->space_before->space_after
425
426 The indent space length is three and JSON::XS cannot change the indent
427 space length.
428
429 indent
430 $json = $json->indent([$enable])
431
432 $enabled = $json->get_indent
433
434 If $enable is true (or missing), then the "encode" method will use a
435 multiline format as output, putting every array member or object/hash
436 key-value pair into its own line, identifying them properly.
437
438 If $enable is false, no newlines or indenting will be produced, and the
439 resulting JSON text is guaranteed not to contain any "newlines".
440
441 This setting has no effect when decoding JSON texts.
442
443 The indent space length is three. With JSON::PP, you can also access
444 "indent_length" to change indent space length.
445
446 space_before
447 $json = $json->space_before([$enable])
448
449 $enabled = $json->get_space_before
450
451 If $enable is true (or missing), then the "encode" method will add an
452 extra optional space before the ":" separating keys from values in JSON
453 objects.
454
455 If $enable is false, then the "encode" method will not add any extra
456 space at those places.
457
458 This setting has no effect when decoding JSON texts.
459
460 Example, space_before enabled, space_after and indent disabled:
461
462 {"key" :"value"}
463
464 space_after
465 $json = $json->space_after([$enable])
466
467 $enabled = $json->get_space_after
468
469 If $enable is true (or missing), then the "encode" method will add an
470 extra optional space after the ":" separating keys from values in JSON
471 objects and extra whitespace after the "," separating key-value pairs
472 and array members.
473
474 If $enable is false, then the "encode" method will not add any extra
475 space at those places.
476
477 This setting has no effect when decoding JSON texts.
478
479 Example, space_before and indent disabled, space_after enabled:
480
481 {"key": "value"}
482
483 relaxed
484 $json = $json->relaxed([$enable])
485
486 $enabled = $json->get_relaxed
487
488 If $enable is true (or missing), then "decode" will accept some
489 extensions to normal JSON syntax (see below). "encode" will not be
490 affected in anyway. Be aware that this option makes you accept invalid
491 JSON texts as if they were valid!. I suggest only to use this option to
492 parse application-specific files written by humans (configuration
493 files, resource files etc.)
494
495 If $enable is false (the default), then "decode" will only accept valid
496 JSON texts.
497
498 Currently accepted extensions are:
499
500 · list items can have an end-comma
501
502 JSON separates array elements and key-value pairs with commas. This
503 can be annoying if you write JSON texts manually and want to be
504 able to quickly append elements, so this extension accepts comma at
505 the end of such items not just between them:
506
507 [
508 1,
509 2, <- this comma not normally allowed
510 ]
511 {
512 "k1": "v1",
513 "k2": "v2", <- this comma not normally allowed
514 }
515
516 · shell-style '#'-comments
517
518 Whenever JSON allows whitespace, shell-style comments are
519 additionally allowed. They are terminated by the first carriage-
520 return or line-feed character, after which more white-space and
521 comments are allowed.
522
523 [
524 1, # this comment not allowed in JSON
525 # neither this one...
526 ]
527
528 canonical
529 $json = $json->canonical([$enable])
530
531 $enabled = $json->get_canonical
532
533 If $enable is true (or missing), then the "encode" method will output
534 JSON objects by sorting their keys. This is adding a comparatively high
535 overhead.
536
537 If $enable is false, then the "encode" method will output key-value
538 pairs in the order Perl stores them (which will likely change between
539 runs of the same script).
540
541 This option is useful if you want the same data structure to be encoded
542 as the same JSON text (given the same overall settings). If it is
543 disabled, the same hash might be encoded differently even if contains
544 the same data, as key-value pairs have no inherent ordering in Perl.
545
546 This setting has no effect when decoding JSON texts.
547
548 allow_nonref
549 $json = $json->allow_nonref([$enable])
550
551 $enabled = $json->get_allow_nonref
552
553 If $enable is true (or missing), then the "encode" method can convert a
554 non-reference into its corresponding string, number or null JSON value,
555 which is an extension to RFC4627. Likewise, "decode" will accept those
556 JSON values instead of croaking.
557
558 If $enable is false, then the "encode" method will croak if it isn't
559 passed an arrayref or hashref, as JSON texts must either be an object
560 or array. Likewise, "decode" will croak if given something that is not
561 a JSON object or array.
562
563 JSON->new->allow_nonref->encode ("Hello, World!")
564 => "Hello, World!"
565
566 allow_unknown
567 $json = $json->allow_unknown ([$enable])
568
569 $enabled = $json->get_allow_unknown
570
571 If $enable is true (or missing), then "encode" will *not* throw an
572 exception when it encounters values it cannot represent in JSON (for
573 example, filehandles) but instead will encode a JSON "null" value.
574 Note that blessed objects are not included here and are handled
575 separately by c<allow_nonref>.
576
577 If $enable is false (the default), then "encode" will throw an
578 exception when it encounters anything it cannot encode as JSON.
579
580 This option does not affect "decode" in any way, and it is recommended
581 to leave it off unless you know your communications partner.
582
583 allow_blessed
584 $json = $json->allow_blessed([$enable])
585
586 $enabled = $json->get_allow_blessed
587
588 If $enable is true (or missing), then the "encode" method will not barf
589 when it encounters a blessed reference. Instead, the value of the
590 convert_blessed option will decide whether "null" ("convert_blessed"
591 disabled or no "TO_JSON" method found) or a representation of the
592 object ("convert_blessed" enabled and "TO_JSON" method found) is being
593 encoded. Has no effect on "decode".
594
595 If $enable is false (the default), then "encode" will throw an
596 exception when it encounters a blessed object.
597
598 convert_blessed
599 $json = $json->convert_blessed([$enable])
600
601 $enabled = $json->get_convert_blessed
602
603 If $enable is true (or missing), then "encode", upon encountering a
604 blessed object, will check for the availability of the "TO_JSON" method
605 on the object's class. If found, it will be called in scalar context
606 and the resulting scalar will be encoded instead of the object. If no
607 "TO_JSON" method is found, the value of "allow_blessed" will decide
608 what to do.
609
610 The "TO_JSON" method may safely call die if it wants. If "TO_JSON"
611 returns other blessed objects, those will be handled in the same way.
612 "TO_JSON" must take care of not causing an endless recursion cycle (==
613 crash) in this case. The name of "TO_JSON" was chosen because other
614 methods called by the Perl core (== not by the user of the object) are
615 usually in upper case letters and to avoid collisions with the
616 "to_json" function or method.
617
618 This setting does not yet influence "decode" in any way.
619
620 If $enable is false, then the "allow_blessed" setting will decide what
621 to do when a blessed object is found.
622
623 convert_blessed_universally mode
624 If use "JSON" with "-convert_blessed_universally", the
625 "UNIVERSAL::TO_JSON" subroutine is defined as the below code:
626
627 *UNIVERSAL::TO_JSON = sub {
628 my $b_obj = B::svref_2object( $_[0] );
629 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
630 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
631 : undef
632 ;
633 }
634
635 This will cause that "encode" method converts simple blessed
636 objects into JSON objects as non-blessed object.
637
638 JSON -convert_blessed_universally;
639 $json->allow_blessed->convert_blessed->encode( $blessed_object )
640
641 This feature is experimental and may be removed in the future.
642
643 filter_json_object
644 $json = $json->filter_json_object([$coderef])
645
646 When $coderef is specified, it will be called from "decode" each time
647 it decodes a JSON object. The only argument passed to the coderef is a
648 reference to the newly-created hash. If the code references returns a
649 single scalar (which need not be a reference), this value (i.e. a copy
650 of that scalar to avoid aliasing) is inserted into the deserialised
651 data structure. If it returns an empty list (NOTE: not "undef", which
652 is a valid scalar), the original deserialised hash will be inserted.
653 This setting can slow down decoding considerably.
654
655 When $coderef is omitted or undefined, any existing callback will be
656 removed and "decode" will not change the deserialised hash in any way.
657
658 Example, convert all JSON objects into the integer 5:
659
660 my $js = JSON->new->filter_json_object (sub { 5 });
661 # returns [5]
662 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
663 # throw an exception because allow_nonref is not enabled
664 # so a lone 5 is not allowed.
665 $js->decode ('{"a":1, "b":2}');
666
667 filter_json_single_key_object
668 $json = $json->filter_json_single_key_object($key [=> $coderef])
669
670 Works remotely similar to "filter_json_object", but is only called for
671 JSON objects having a single key named $key.
672
673 This $coderef is called before the one specified via
674 "filter_json_object", if any. It gets passed the single value in the
675 JSON object. If it returns a single value, it will be inserted into the
676 data structure. If it returns nothing (not even "undef" but the empty
677 list), the callback from "filter_json_object" will be called next, as
678 if no single-key callback were specified.
679
680 If $coderef is omitted or undefined, the corresponding callback will be
681 disabled. There can only ever be one callback for a given key.
682
683 As this callback gets called less often then the "filter_json_object"
684 one, decoding speed will not usually suffer as much. Therefore, single-
685 key objects make excellent targets to serialise Perl objects into,
686 especially as single-key JSON objects are as close to the type-tagged
687 value concept as JSON gets (it's basically an ID/VALUE tuple). Of
688 course, JSON does not support this in any way, so you need to make sure
689 your data never looks like a serialised Perl hash.
690
691 Typical names for the single object key are "__class_whatever__", or
692 "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or even
693 things like "__class_md5sum(classname)__", to reduce the risk of
694 clashing with real hashes.
695
696 Example, decode JSON objects of the form "{ "__widget__" => <id> }"
697 into the corresponding $WIDGET{<id>} object:
698
699 # return whatever is in $WIDGET{5}:
700 JSON
701 ->new
702 ->filter_json_single_key_object (__widget__ => sub {
703 $WIDGET{ $_[0] }
704 })
705 ->decode ('{"__widget__": 5')
706
707 # this can be used with a TO_JSON method in some "widget" class
708 # for serialisation to json:
709 sub WidgetBase::TO_JSON {
710 my ($self) = @_;
711
712 unless ($self->{id}) {
713 $self->{id} = ..get..some..id..;
714 $WIDGET{$self->{id}} = $self;
715 }
716
717 { __widget__ => $self->{id} }
718 }
719
720 shrink
721 $json = $json->shrink([$enable])
722
723 $enabled = $json->get_shrink
724
725 With JSON::XS, this flag resizes strings generated by either "encode"
726 or "decode" to their minimum size possible. This can save memory when
727 your JSON texts are either very very long or you have many short
728 strings. It will also try to downgrade any strings to octet-form if
729 possible: perl stores strings internally either in an encoding called
730 UTF-X or in octet-form. The latter cannot store everything but uses
731 less space in general (and some buggy Perl or C code might even rely on
732 that internal representation being used).
733
734 With JSON::PP, it is noop about resizing strings but tries
735 "utf8::downgrade" to the returned string by "encode". See to utf8.
736
737 See to "OBJECT-ORIENTED INTERFACE" in JSON::XS and "METHODS" in
738 JSON::PP.
739
740 max_depth
741 $json = $json->max_depth([$maximum_nesting_depth])
742
743 $max_depth = $json->get_max_depth
744
745 Sets the maximum nesting level (default 512) accepted while encoding or
746 decoding. If a higher nesting level is detected in JSON text or a Perl
747 data structure, then the encoder and decoder will stop and croak at
748 that point.
749
750 Nesting level is defined by number of hash- or arrayrefs that the
751 encoder needs to traverse to reach a given point or the number of "{"
752 or "[" characters without their matching closing parenthesis crossed to
753 reach a given character in a string.
754
755 If no argument is given, the highest possible setting will be used,
756 which is rarely useful.
757
758 Note that nesting is implemented by recursion in C. The default value
759 has been chosen to be as large as typical operating systems allow
760 without crashing. (JSON::XS)
761
762 With JSON::PP as the backend, when a large value (100 or more) was set
763 and it de/encodes a deep nested object/text, it may raise a warning
764 'Deep recursion on subroutine' at the perl runtime phase.
765
766 See "SECURITY CONSIDERATIONS" in JSON::XS for more info on why this is
767 useful.
768
769 max_size
770 $json = $json->max_size([$maximum_string_size])
771
772 $max_size = $json->get_max_size
773
774 Set the maximum length a JSON text may have (in bytes) where decoding
775 is being attempted. The default is 0, meaning no limit. When "decode"
776 is called on a string that is longer then this many bytes, it will not
777 attempt to decode the string but throw an exception. This setting has
778 no effect on "encode" (yet).
779
780 If no argument is given, the limit check will be deactivated (same as
781 when 0 is specified).
782
783 See "SECURITY CONSIDERATIONS" in JSON::XS, below, for more info on why
784 this is useful.
785
786 encode
787 $json_text = $json->encode($perl_scalar)
788
789 Converts the given Perl data structure (a simple scalar or a reference
790 to a hash or array) to its JSON representation. Simple scalars will be
791 converted into JSON string or number sequences, while references to
792 arrays become JSON arrays and references to hashes become JSON objects.
793 Undefined Perl values (e.g. "undef") become JSON "null" values.
794 References to the integers 0 and 1 are converted into "true" and
795 "false".
796
797 decode
798 $perl_scalar = $json->decode($json_text)
799
800 The opposite of "encode": expects a JSON text and tries to parse it,
801 returning the resulting simple scalar or reference. Croaks on error.
802
803 JSON numbers and strings become simple Perl scalars. JSON arrays become
804 Perl arrayrefs and JSON objects become Perl hashrefs. "true" becomes 1
805 ("JSON::true"), "false" becomes 0 ("JSON::false") and "null" becomes
806 "undef".
807
808 decode_prefix
809 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
810
811 This works like the "decode" method, but instead of raising an
812 exception when there is trailing garbage after the first JSON object,
813 it will silently stop parsing there and return the number of characters
814 consumed so far.
815
816 JSON->new->decode_prefix ("[1] the tail")
817 => ([], 3)
818
819 See to "OBJECT-ORIENTED INTERFACE" in JSON::XS
820
821 property
822 $boolean = $json->property($property_name)
823
824 Returns a boolean value about above some properties.
825
826 The available properties are "ascii", "latin1", "utf8",
827 "indent","space_before", "space_after", "relaxed", "canonical",
828 "allow_nonref", "allow_unknown", "allow_blessed", "convert_blessed",
829 "shrink", "max_depth" and "max_size".
830
831 $boolean = $json->property('utf8');
832 => 0
833 $json->utf8;
834 $boolean = $json->property('utf8');
835 => 1
836
837 Sets the property with a given boolean value.
838
839 $json = $json->property($property_name => $boolean);
840
841 With no argument, it returns all the above properties as a hash
842 reference.
843
844 $flag_hashref = $json->property();
845
847 Most of this section are copied and modified from "INCREMENTAL PARSING"
848 in JSON::XS.
849
850 In some cases, there is the need for incremental parsing of JSON texts.
851 This module does allow you to parse a JSON stream incrementally. It
852 does so by accumulating text until it has a full JSON object, which it
853 then can decode. This process is similar to using "decode_prefix" to
854 see if a full JSON object is available, but is much more efficient (and
855 can be implemented with a minimum of method calls).
856
857 The backend module will only attempt to parse the JSON text once it is
858 sure it has enough text to get a decisive result, using a very simple
859 but truly incremental parser. This means that it sometimes won't stop
860 as early as the full parser, for example, it doesn't detect parenthesis
861 mismatches. The only thing it guarantees is that it starts decoding as
862 soon as a syntactically valid JSON text has been seen. This means you
863 need to set resource limits (e.g. "max_size") to ensure the parser will
864 stop parsing in the presence if syntax errors.
865
866 The following methods implement this incremental parser.
867
868 incr_parse
869 $json->incr_parse( [$string] ) # void context
870
871 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
872
873 @obj_or_empty = $json->incr_parse( [$string] ) # list context
874
875 This is the central parsing function. It can both append new text and
876 extract objects from the stream accumulated so far (both of these
877 functions are optional).
878
879 If $string is given, then this string is appended to the already
880 existing JSON fragment stored in the $json object.
881
882 After that, if the function is called in void context, it will simply
883 return without doing anything further. This can be used to add more
884 text in as many chunks as you want.
885
886 If the method is called in scalar context, then it will try to extract
887 exactly one JSON object. If that is successful, it will return this
888 object, otherwise it will return "undef". If there is a parse error,
889 this method will croak just as "decode" would do (one can then use
890 "incr_skip" to skip the erroneous part). This is the most common way of
891 using the method.
892
893 And finally, in list context, it will try to extract as many objects
894 from the stream as it can find and return them, or the empty list
895 otherwise. For this to work, there must be no separators between the
896 JSON objects or arrays, instead they must be concatenated back-to-back.
897 If an error occurs, an exception will be raised as in the scalar
898 context case. Note that in this case, any previously-parsed JSON texts
899 will be lost.
900
901 Example: Parse some JSON arrays/objects in a given string and return
902 them.
903
904 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
905
906 incr_text
907 $lvalue_string = $json->incr_text
908
909 This method returns the currently stored JSON fragment as an lvalue,
910 that is, you can manipulate it. This only works when a preceding call
911 to "incr_parse" in scalar context successfully returned an object.
912 Under all other circumstances you must not call this function (I mean
913 it. although in simple tests it might actually work, it will fail
914 under real world conditions). As a special exception, you can also call
915 this method before having parsed anything.
916
917 This function is useful in two cases: a) finding the trailing text
918 after a JSON object or b) parsing multiple JSON objects separated by
919 non-JSON text (such as commas).
920
921 $json->incr_text =~ s/\s*,\s*//;
922
923 In Perl 5.005, "lvalue" attribute is not available. You must write
924 codes like the below:
925
926 $string = $json->incr_text;
927 $string =~ s/\s*,\s*//;
928 $json->incr_text( $string );
929
930 incr_skip
931 $json->incr_skip
932
933 This will reset the state of the incremental parser and will remove the
934 parsed text from the input buffer. This is useful after "incr_parse"
935 died, in which case the input buffer and incremental parser state is
936 left unchanged, to skip the text parsed so far and to reset the parse
937 state.
938
939 incr_reset
940 $json->incr_reset
941
942 This completely resets the incremental parser, that is, after this
943 call, it will be as if the parser had never parsed anything.
944
945 This is useful if you want to repeatedly parse JSON objects and want to
946 ignore any trailing data, which means you have to reset the parser
947 after each successful decode.
948
949 See to "INCREMENTAL PARSING" in JSON::XS for examples.
950
952 The below methods are JSON::PP own methods, so when "JSON" works with
953 JSON::PP (i.e. the created object is a JSON::PP object), available.
954 See to "JSON::PP OWN METHODS" in JSON::PP in detail.
955
956 If you use "JSON" with additional "-support_by_pp", some methods are
957 available even with JSON::XS. See to "USE PP FEATURES EVEN THOUGH XS
958 BACKEND".
959
960 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
961
962 use JSON -support_by_pp;
963
964 my $json = JSON->new;
965 $json->allow_nonref->escape_slash->encode("/");
966
967 # functional interfaces too.
968 print to_json(["/"], {escape_slash => 1});
969 print from_json('["foo"]', {utf8 => 1});
970
971 If you do not want to all functions but "-support_by_pp", use
972 "-no_export".
973
974 use JSON -support_by_pp, -no_export;
975 # functional interfaces are not exported.
976
977 allow_singlequote
978 $json = $json->allow_singlequote([$enable])
979
980 If $enable is true (or missing), then "decode" will accept any JSON
981 strings quoted by single quotations that are invalid JSON format.
982
983 $json->allow_singlequote->decode({"foo":'bar'});
984 $json->allow_singlequote->decode({'foo':"bar"});
985 $json->allow_singlequote->decode({'foo':'bar'});
986
987 As same as the "relaxed" option, this option may be used to parse
988 application-specific files written by humans.
989
990 allow_barekey
991 $json = $json->allow_barekey([$enable])
992
993 If $enable is true (or missing), then "decode" will accept bare keys of
994 JSON object that are invalid JSON format.
995
996 As same as the "relaxed" option, this option may be used to parse
997 application-specific files written by humans.
998
999 $json->allow_barekey->decode('{foo:"bar"}');
1000
1001 allow_bignum
1002 $json = $json->allow_bignum([$enable])
1003
1004 If $enable is true (or missing), then "decode" will convert the big
1005 integer Perl cannot handle as integer into a Math::BigInt object and
1006 convert a floating number (any) into a Math::BigFloat.
1007
1008 On the contrary, "encode" converts "Math::BigInt" objects and
1009 "Math::BigFloat" objects into JSON numbers with "allow_blessed" enable.
1010
1011 $json->allow_nonref->allow_blessed->allow_bignum;
1012 $bigfloat = $json->decode('2.000000000000000000000000001');
1013 print $json->encode($bigfloat);
1014 # => 2.000000000000000000000000001
1015
1016 See to MAPPING about the conversion of JSON number.
1017
1018 loose
1019 $json = $json->loose([$enable])
1020
1021 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON
1022 strings and the module doesn't allow to "decode" to these (except for
1023 \x2f). If $enable is true (or missing), then "decode" will accept
1024 these unescaped strings.
1025
1026 $json->loose->decode(qq|["abc
1027 def"]|);
1028
1029 See to "JSON::PP OWN METHODS" in JSON::PP.
1030
1031 escape_slash
1032 $json = $json->escape_slash([$enable])
1033
1034 According to JSON Grammar, slash (U+002F) is escaped. But by default
1035 JSON backend modules encode strings without escaping slash.
1036
1037 If $enable is true (or missing), then "encode" will escape slashes.
1038
1039 indent_length
1040 $json = $json->indent_length($length)
1041
1042 With JSON::XS, The indent space length is 3 and cannot be changed.
1043 With JSON::PP, it sets the indent space length with the given $length.
1044 The default is 3. The acceptable range is 0 to 15.
1045
1046 sort_by
1047 $json = $json->sort_by($function_name)
1048 $json = $json->sort_by($subroutine_ref)
1049
1050 If $function_name or $subroutine_ref are set, its sort routine are
1051 used.
1052
1053 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
1054 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1055
1056 $js = $pc->sort_by('own_sort')->encode($obj);
1057 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1058
1059 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
1060
1061 As the sorting routine runs in the JSON::PP scope, the given subroutine
1062 name and the special variables $a, $b will begin with 'JSON::PP::'.
1063
1064 If $integer is set, then the effect is same as "canonical" on.
1065
1066 See to "JSON::PP OWN METHODS" in JSON::PP.
1067
1069 This section is copied from JSON::XS and modified to "JSON". JSON::XS
1070 and JSON::PP mapping mechanisms are almost equivalent.
1071
1072 See to "MAPPING" in JSON::XS.
1073
1074 JSON -> PERL
1075 object
1076 A JSON object becomes a reference to a hash in Perl. No ordering of
1077 object keys is preserved (JSON does not preserver object key
1078 ordering itself).
1079
1080 array
1081 A JSON array becomes a reference to an array in Perl.
1082
1083 string
1084 A JSON string becomes a string scalar in Perl - Unicode codepoints
1085 in JSON are represented by the same codepoints in the Perl string,
1086 so no manual decoding is necessary.
1087
1088 number
1089 A JSON number becomes either an integer, numeric (floating point)
1090 or string scalar in perl, depending on its range and any fractional
1091 parts. On the Perl level, there is no difference between those as
1092 Perl handles all the conversion details, but an integer may take
1093 slightly less memory and might represent more values exactly than
1094 floating point numbers.
1095
1096 If the number consists of digits only, "JSON" will try to represent
1097 it as an integer value. If that fails, it will try to represent it
1098 as a numeric (floating point) value if that is possible without
1099 loss of precision. Otherwise it will preserve the number as a
1100 string value (in which case you lose roundtripping ability, as the
1101 JSON number will be re-encoded to a JSON string).
1102
1103 Numbers containing a fractional or exponential part will always be
1104 represented as numeric (floating point) values, possibly at a loss
1105 of precision (in which case you might lose perfect roundtripping
1106 ability, but the JSON number will still be re-encoded as a JSON
1107 number).
1108
1109 Note that precision is not accuracy - binary floating point values
1110 cannot represent most decimal fractions exactly, and when
1111 converting from and to floating point, "JSON" only guarantees
1112 precision up to but not including the least significant bit.
1113
1114 If the backend is JSON::PP and "allow_bignum" is enable, the big
1115 integers and the numeric can be optionally converted into
1116 Math::BigInt and Math::BigFloat objects.
1117
1118 true, false
1119 These JSON atoms become "JSON::true" and "JSON::false",
1120 respectively. They are overloaded to act almost exactly like the
1121 numbers 1 and 0. You can check whether a scalar is a JSON boolean
1122 by using the "JSON::is_bool" function.
1123
1124 If "JSON::true" and "JSON::false" are used as strings or compared
1125 as strings, they represent as "true" and "false" respectively.
1126
1127 print JSON::true . "\n";
1128 => true
1129 print JSON::true + 1;
1130 => 1
1131
1132 ok(JSON::true eq 'true');
1133 ok(JSON::true eq '1');
1134 ok(JSON::true == 1);
1135
1136 "JSON" will install these missing overloading features to the
1137 backend modules.
1138
1139 null
1140 A JSON null atom becomes "undef" in Perl.
1141
1142 "JSON::null" returns "undef".
1143
1144 PERL -> JSON
1145 The mapping from Perl to JSON is slightly more difficult, as Perl is a
1146 truly typeless language, so we can only guess which JSON type is meant
1147 by a Perl value.
1148
1149 hash references
1150 Perl hash references become JSON objects. As there is no inherent
1151 ordering in hash keys (or JSON objects), they will usually be
1152 encoded in a pseudo-random order that can change between runs of
1153 the same program but stays generally the same within a single run
1154 of a program. "JSON" optionally sort the hash keys (determined by
1155 the canonical flag), so the same data structure will serialise to
1156 the same JSON text (given same settings and version of JSON::XS),
1157 but this incurs a runtime overhead and is only rarely useful, e.g.
1158 when you want to compare some JSON text against another for
1159 equality.
1160
1161 In future, the ordered object feature will be added to JSON::PP
1162 using "tie" mechanism.
1163
1164 array references
1165 Perl array references become JSON arrays.
1166
1167 other references
1168 Other unblessed references are generally not allowed and will cause
1169 an exception to be thrown, except for references to the integers 0
1170 and 1, which get turned into "false" and "true" atoms in JSON. You
1171 can also use "JSON::false" and "JSON::true" to improve readability.
1172
1173 to_json [\0,JSON::true] # yields [false,true]
1174
1175 JSON::true, JSON::false, JSON::null
1176 These special values become JSON true and JSON false values,
1177 respectively. You can also use "\1" and "\0" directly if you want.
1178
1179 JSON::null returns "undef".
1180
1181 blessed objects
1182 Blessed objects are not directly representable in JSON. See the
1183 "allow_blessed" and "convert_blessed" methods on various options on
1184 how to deal with this: basically, you can choose between throwing
1185 an exception, encoding the reference as if it weren't blessed, or
1186 provide your own serialiser method.
1187
1188 With "convert_blessed_universally" mode, "encode" converts blessed
1189 hash references or blessed array references (contains other blessed
1190 references) into JSON members and arrays.
1191
1192 use JSON -convert_blessed_universally;
1193 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
1194
1195 See to convert_blessed.
1196
1197 simple scalars
1198 Simple Perl scalars (any scalar that is not a reference) are the
1199 most difficult objects to encode: JSON::XS and JSON::PP will encode
1200 undefined scalars as JSON "null" values, scalars that have last
1201 been used in a string context before encoding as JSON strings, and
1202 anything else as number value:
1203
1204 # dump as number
1205 encode_json [2] # yields [2]
1206 encode_json [-3.0e17] # yields [-3e+17]
1207 my $value = 5; encode_json [$value] # yields [5]
1208
1209 # used as string, so dump as string
1210 print $value;
1211 encode_json [$value] # yields ["5"]
1212
1213 # undef becomes null
1214 encode_json [undef] # yields [null]
1215
1216 You can force the type to be a string by stringifying it:
1217
1218 my $x = 3.1; # some variable containing a number
1219 "$x"; # stringified
1220 $x .= ""; # another, more awkward way to stringify
1221 print $x; # perl does it for you, too, quite often
1222
1223 You can force the type to be a number by numifying it:
1224
1225 my $x = "3"; # some variable containing a string
1226 $x += 0; # numify it, ensuring it will be dumped as a number
1227 $x *= 1; # same thing, the choice is yours.
1228
1229 You can not currently force the type in other, less obscure, ways.
1230
1231 Note that numerical precision has the same meaning as under Perl
1232 (so binary to decimal conversion follows the same rules as in Perl,
1233 which can differ to other languages). Also, your perl interpreter
1234 might expose extensions to the floating point numbers of your
1235 platform, such as infinities or NaN's - these cannot be represented
1236 in JSON, and it is an error to pass those in.
1237
1238 Big Number
1239 If the backend is JSON::PP and "allow_bignum" is enable, "encode"
1240 converts "Math::BigInt" objects and "Math::BigFloat" objects into
1241 JSON numbers.
1242
1244 See to "JSON and ECMAscript" in JSON::XS.
1245
1247 JSON is not a subset of YAML. See to "JSON and YAML" in JSON::XS.
1248
1250 When you use "JSON", "JSON" tries to "use" JSON::XS. If this call
1251 failed, it will "uses" JSON::PP. The required JSON::XS version is 2.2
1252 or later.
1253
1254 The "JSON" constructor method returns an object inherited from the
1255 backend module, and JSON::XS object is a blessed scalar reference while
1256 JSON::PP is a blessed hash reference.
1257
1258 So, your program should not depend on the backend module, especially
1259 returned objects should not be modified.
1260
1261 my $json = JSON->new; # XS or PP?
1262 $json->{stash} = 'this is xs object'; # this code may raise an error!
1263
1264 To check the backend module, there are some methods - "backend",
1265 "is_pp" and "is_xs".
1266
1267 JSON->backend; # 'JSON::XS' or 'JSON::PP'
1268
1269 JSON->backend->is_pp: # 0 or 1
1270
1271 JSON->backend->is_xs: # 1 or 0
1272
1273 $json->is_xs; # 1 or 0
1274
1275 $json->is_pp; # 0 or 1
1276
1277 If you set an environment variable "PERL_JSON_BACKEND", the calling
1278 action will be changed.
1279
1280 PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
1281 Always use JSON::PP
1282
1283 PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
1284 (The default) Use compiled JSON::XS if it is properly compiled &
1285 installed, otherwise use JSON::PP.
1286
1287 PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
1288 Always use compiled JSON::XS, die if it isn't properly compiled &
1289 installed.
1290
1291 PERL_JSON_BACKEND = 'JSON::backportPP'
1292 Always use JSON::backportPP. JSON::backportPP is JSON::PP back
1293 port module. "JSON" includes JSON::backportPP instead of JSON::PP.
1294
1295 These ideas come from DBI::PurePerl mechanism.
1296
1297 example:
1298
1299 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
1300 use JSON; # always uses JSON::PP
1301
1302 In future, it may be able to specify another module.
1303
1305 Many methods are available with either JSON::XS or JSON::PP and when
1306 the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS
1307 unsupported) method is called, it will "warn" and be noop.
1308
1309 But If you "use" "JSON" passing the optional string "-support_by_pp",
1310 it makes a part of those unsupported methods available. This feature
1311 is achieved by using JSON::PP in "de/encode".
1312
1313 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
1314 use JSON -support_by_pp;
1315 my $json = JSON->new;
1316 $json->allow_nonref->escape_slash->encode("/");
1317
1318 At this time, the returned object is a "JSON::Backend::XS::Supportable"
1319 object (re-blessed XS object), and by checking JSON::XS unsupported
1320 flags in de/encoding, can support some unsupported methods - "loose",
1321 "allow_bignum", "allow_barekey", "allow_singlequote", "escape_slash"
1322 and "indent_length".
1323
1324 When any unsupported methods are not enable, "XS de/encode" will be
1325 used as is. The switch is achieved by changing the symbolic tables.
1326
1327 "-support_by_pp" is effective only when the backend module is JSON::XS
1328 and it makes the de/encoding speed down a bit.
1329
1330 See to "JSON::PP SUPPORT METHODS".
1331
1333 There are big incompatibility between new version (2.00) and old
1334 (1.xx). If you use old "JSON" 1.xx in your code, please check it.
1335
1336 See to "Transition ways from 1.xx to 2.xx."
1337
1338 jsonToObj and objToJson are obsoleted.
1339 Non Perl-style name "jsonToObj" and "objToJson" are obsoleted (but
1340 not yet deleted from the source). If you use these functions in
1341 your code, please replace them with "from_json" and "to_json".
1342
1343 Global variables are no longer available.
1344 "JSON" class variables - $JSON::AUTOCONVERT, $JSON::BareKey, etc...
1345 - are not available any longer. Instead, various features can be
1346 used through object methods.
1347
1348 Package JSON::Converter and JSON::Parser are deleted.
1349 Now "JSON" bundles with JSON::PP which can handle JSON more
1350 properly than them.
1351
1352 Package JSON::NotString is deleted.
1353 There was "JSON::NotString" class which represents JSON value
1354 "true", "false", "null" and numbers. It was deleted and replaced by
1355 "JSON::Boolean".
1356
1357 "JSON::Boolean" represents "true" and "false".
1358
1359 "JSON::Boolean" does not represent "null".
1360
1361 "JSON::null" returns "undef".
1362
1363 "JSON" makes JSON::XS::Boolean and JSON::PP::Boolean is-a relation
1364 to JSON::Boolean.
1365
1366 function JSON::Number is obsoleted.
1367 "JSON::Number" is now needless because JSON::XS and JSON::PP have
1368 round-trip integrity.
1369
1370 JSONRPC modules are deleted.
1371 Perl implementation of JSON-RPC protocol - "JSONRPC ",
1372 "JSONRPC::Transport::HTTP" and "Apache::JSONRPC " are deleted in
1373 this distribution. Instead of them, there is JSON::RPC which
1374 supports JSON-RPC protocol version 1.1.
1375
1376 Transition ways from 1.xx to 2.xx.
1377 You should set "suport_by_pp" mode firstly, because it is always
1378 successful for the below codes even with JSON::XS.
1379
1380 use JSON -support_by_pp;
1381
1382 Exported jsonToObj (simple)
1383 from_json($json_text);
1384
1385 Exported objToJson (simple)
1386 to_json($perl_scalar);
1387
1388 Exported jsonToObj (advanced)
1389 $flags = {allow_barekey => 1, allow_singlequote => 1};
1390 from_json($json_text, $flags);
1391
1392 equivalent to:
1393
1394 $JSON::BareKey = 1;
1395 $JSON::QuotApos = 1;
1396 jsonToObj($json_text);
1397
1398 Exported objToJson (advanced)
1399 $flags = {allow_blessed => 1, allow_barekey => 1};
1400 to_json($perl_scalar, $flags);
1401
1402 equivalent to:
1403
1404 $JSON::BareKey = 1;
1405 objToJson($perl_scalar);
1406
1407 jsonToObj as object method
1408 $json->decode($json_text);
1409
1410 objToJson as object method
1411 $json->encode($perl_scalar);
1412
1413 new method with parameters
1414 The "new" method in 2.x takes any parameters no longer. You can
1415 set parameters instead;
1416
1417 $json = JSON->new->pretty;
1418
1419 $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
1420 If "indent" is enable, that means $JSON::Pretty flag set. And
1421 $JSON::Delimiter was substituted by "space_before" and
1422 "space_after". In conclusion:
1423
1424 $json->indent->space_before->space_after;
1425
1426 Equivalent to:
1427
1428 $json->pretty;
1429
1430 To change indent length, use "indent_length".
1431
1432 (Only with JSON::PP, if "-support_by_pp" is not used.)
1433
1434 $json->pretty->indent_length(2)->encode($perl_scalar);
1435
1436 $JSON::BareKey
1437 (Only with JSON::PP, if "-support_by_pp" is not used.)
1438
1439 $json->allow_barekey->decode($json_text)
1440
1441 $JSON::ConvBlessed
1442 use "-convert_blessed_universally". See to convert_blessed.
1443
1444 $JSON::QuotApos
1445 (Only with JSON::PP, if "-support_by_pp" is not used.)
1446
1447 $json->allow_singlequote->decode($json_text)
1448
1449 $JSON::SingleQuote
1450 Disable. "JSON" does not make such a invalid JSON string any
1451 longer.
1452
1453 $JSON::KeySort
1454 $json->canonical->encode($perl_scalar)
1455
1456 This is the ascii sort.
1457
1458 If you want to use with your own sort routine, check the "sort_by"
1459 method.
1460
1461 (Only with JSON::PP, even if "-support_by_pp" is used currently.)
1462
1463 $json->sort_by($sort_routine_ref)->encode($perl_scalar)
1464
1465 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
1466
1467 Can't access $a and $b but $JSON::PP::a and $JSON::PP::b.
1468
1469 $JSON::SkipInvalid
1470 $json->allow_unknown
1471
1472 $JSON::AUTOCONVERT
1473 Needless. "JSON" backend modules have the round-trip integrity.
1474
1475 $JSON::UTF8
1476 Needless because "JSON" (JSON::XS/JSON::PP) sets the UTF8 flag on
1477 properly.
1478
1479 # With UTF8-flagged strings
1480
1481 $json->allow_nonref;
1482 $str = chr(1000); # UTF8-flagged
1483
1484 $json_text = $json->utf8(0)->encode($str);
1485 utf8::is_utf8($json_text);
1486 # true
1487 $json_text = $json->utf8(1)->encode($str);
1488 utf8::is_utf8($json_text);
1489 # false
1490
1491 $str = '"' . chr(1000) . '"'; # UTF8-flagged
1492
1493 $perl_scalar = $json->utf8(0)->decode($str);
1494 utf8::is_utf8($perl_scalar);
1495 # true
1496 $perl_scalar = $json->utf8(1)->decode($str);
1497 # died because of 'Wide character in subroutine'
1498
1499 See to "A FEW NOTES ON UNICODE AND PERL" in JSON::XS.
1500
1501 $JSON::UnMapping
1502 Disable. See to MAPPING.
1503
1504 $JSON::SelfConvert
1505 This option was deleted. Instead of it, if a given blessed object
1506 has the "TO_JSON" method, "TO_JSON" will be executed with
1507 "convert_blessed".
1508
1509 $json->convert_blessed->encode($blessed_hashref_or_arrayref)
1510 # if need, call allow_blessed
1511
1512 Note that it was "toJson" in old version, but now not "toJson" but
1513 "TO_JSON".
1514
1516 example programs
1517
1519 No test with JSON::PP. If with JSON::XS, See to "THREADS" in JSON::XS.
1520
1522 Please report bugs relevant to "JSON" to <makamaka[at]cpan.org>.
1523
1525 Most of the document is copied and modified from JSON::XS doc.
1526
1527 JSON::XS, JSON::PP
1528
1529 "RFC4627"(<http://www.ietf.org/rfc/rfc4627.txt>)
1530
1532 Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
1533
1534 JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
1535
1536 The release of this new version owes to the courtesy of Marc Lehmann.
1537
1539 Copyright 2005-2013 by Makamaka Hannyaharamitu
1540
1541 This library is free software; you can redistribute it and/or modify it
1542 under the same terms as Perl itself.
1543
1544
1545
1546perl v5.16.3 2013-06-05 JSON(3)