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