Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(82)

Side by Side Diff: third_party/JSON/JSON-2.58/README

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

Powered by Google App Engine
This is Rietveld 408576698