1JSON::PP(3)           User Contributed Perl Documentation          JSON::PP(3)
2
3
4

NAME

6       JSON::PP - JSON::XS compatible pure-Perl module.
7

SYNOPSIS

9        use JSON::PP;
10
11        # exported functions, they croak on error
12        # and expect/generate UTF-8
13
14        $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
15        $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;
16
17        # OO-interface
18
19        $coder = JSON::PP->new->ascii->pretty->allow_nonref;
20
21        $json_text   = $json->encode( $perl_scalar );
22        $perl_scalar = $json->decode( $json_text );
23
24        $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
25
26        # Note that JSON version 2.0 and above will automatically use
27        # JSON::XS or JSON::PP, so you should be able to just:
28
29        use JSON;
30

VERSION

32           2.27202
33
34       JSON::XS 2.27 (~2.30) compatible.
35

NOTE

37       JSON::PP had been inculded in JSON distribution (CPAN module).  It was
38       a perl core module in Perl 5.14.
39

DESCRIPTION

41       This module is JSON::XS compatible pure Perl module.  (Perl 5.8 or
42       later is recommended)
43
44       JSON::XS is the fastest and most proper JSON module on CPAN.  It is
45       written by Marc Lehmann in C, so must be compiled and installed in the
46       used environment.
47
48       JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
49
50   FEATURES
51       ·   correct unicode handling
52
53           This module knows how to handle Unicode (depending on Perl
54           version).
55
56           See to "A FEW NOTES ON UNICODE AND PERL" in JSON::XS and "UNICODE
57           HANDLING ON PERLS".
58
59       ·   round-trip integrity
60
61           When you serialise a perl data structure using only data types
62           supported by JSON and Perl, the deserialised data structure is
63           identical on the Perl level. (e.g. the string "2.0" doesn't
64           suddenly become "2" just because it looks like a number). There are
65           minor exceptions to this, read the MAPPING section below to learn
66           about those.
67
68       ·   strict checking of JSON correctness
69
70           There is no guessing, no generating of illegal JSON texts by
71           default, and only JSON is accepted as input by default (the latter
72           is a security feature).  But when some options are set, loose
73           chcking features are available.
74

FUNCTIONAL INTERFACE

76       Some documents are copied and modified from "FUNCTIONAL INTERFACE" in
77       JSON::XS.
78
79   encode_json
80           $json_text = encode_json $perl_scalar
81
82       Converts the given Perl data structure to a UTF-8 encoded, binary
83       string.
84
85       This function call is functionally identical to:
86
87           $json_text = JSON::PP->new->utf8->encode($perl_scalar)
88
89   decode_json
90           $perl_scalar = decode_json $json_text
91
92       The opposite of "encode_json": expects an UTF-8 (binary) string and
93       tries to parse that as an UTF-8 encoded JSON text, returning the
94       resulting reference.
95
96       This function call is functionally identical to:
97
98           $perl_scalar = JSON::PP->new->utf8->decode($json_text)
99
100   JSON::PP::is_bool
101           $is_boolean = JSON::PP::is_bool($scalar)
102
103       Returns true if the passed scalar represents either JSON::PP::true or
104       JSON::PP::false, two constants that act like 1 and 0 respectively and
105       are also used to represent JSON "true" and "false" in Perl strings.
106
107   JSON::PP::true
108       Returns JSON true value which is blessed object.  It "isa"
109       JSON::PP::Boolean object.
110
111   JSON::PP::false
112       Returns JSON false value which is blessed object.  It "isa"
113       JSON::PP::Boolean object.
114
115   JSON::PP::null
116       Returns "undef".
117
118       See MAPPING, below, for more information on how JSON values are mapped
119       to Perl.
120

HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER

122       This section supposes that your perl vresion is 5.8 or later.
123
124       If you know a JSON text from an outer world - a network, a file
125       content, and so on, is encoded in UTF-8, you should use "decode_json"
126       or "JSON" module object with "utf8" enable. And the decoded result will
127       contain UNICODE characters.
128
129         # from network
130         my $json        = JSON::PP->new->utf8;
131         my $json_text   = CGI->new->param( 'json_data' );
132         my $perl_scalar = $json->decode( $json_text );
133
134         # from file content
135         local $/;
136         open( my $fh, '<', 'json.data' );
137         $json_text   = <$fh>;
138         $perl_scalar = decode_json( $json_text );
139
140       If an outer data is not encoded in UTF-8, firstly you should "decode"
141       it.
142
143         use Encode;
144         local $/;
145         open( my $fh, '<', 'json.data' );
146         my $encoding = 'cp932';
147         my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
148
149         # or you can write the below code.
150         #
151         # open( my $fh, "<:encoding($encoding)", 'json.data' );
152         # $unicode_json_text = <$fh>;
153
154       In this case, $unicode_json_text is of course UNICODE string.  So you
155       cannot use "decode_json" nor "JSON" module object with "utf8" enable.
156       Instead of them, you use "JSON" module object with "utf8" disable.
157
158         $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
159
160       Or "encode 'utf8'" and "decode_json":
161
162         $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
163         # this way is not efficient.
164
165       And now, you want to convert your $perl_scalar into JSON data and send
166       it to an outer world - a network or a file content, and so on.
167
168       Your data usually contains UNICODE strings and you want the converted
169       data to be encoded in UTF-8, you should use "encode_json" or "JSON"
170       module object with "utf8" enable.
171
172         print encode_json( $perl_scalar ); # to a network? file? or display?
173         # or
174         print $json->utf8->encode( $perl_scalar );
175
176       If $perl_scalar does not contain UNICODE but $encoding-encoded strings
177       for some reason, then its characters are regarded as latin1 for perl
178       (because it does not concern with your $encoding).  You cannot use
179       "encode_json" nor "JSON" module object with "utf8" enable.  Instead of
180       them, you use "JSON" module object with "utf8" disable.  Note that the
181       resulted text is a UNICODE string but no problem to print it.
182
183         # $perl_scalar contains $encoding encoded string values
184         $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
185         # $unicode_json_text consists of characters less than 0x100
186         print $unicode_json_text;
187
188       Or "decode $encoding" all string values and "encode_json":
189
190         $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
191         # ... do it to each string values, then encode_json
192         $json_text = encode_json( $perl_scalar );
193
194       This method is a proper way but probably not efficient.
195
196       See to Encode, perluniintro.
197

METHODS

199       Basically, check to JSON or JSON::XS.
200
201   new
202           $json = JSON::PP->new
203
204       Rturns a new JSON::PP object that can be used to de/encode JSON
205       strings.
206
207       All boolean flags described below are by default disabled.
208
209       The mutators for flags all return the JSON object again and thus calls
210       can be chained:
211
212          my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
213          => {"a": [1, 2]}
214
215   ascii
216           $json = $json->ascii([$enable])
217
218           $enabled = $json->get_ascii
219
220       If $enable is true (or missing), then the encode method will not
221       generate characters outside the code range 0..127. Any Unicode
222       characters outside that range will be escaped using either a single
223       \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.  (See
224       to "OBJECT-ORIENTED INTERFACE" in JSON::XS).
225
226       In Perl 5.005, there is no character having high value (more than 255).
227       See to "UNICODE HANDLING ON PERLS".
228
229       If $enable is false, then the encode method will not escape Unicode
230       characters unless required by the JSON syntax or other flags. This
231       results in a faster and more compact format.
232
233         JSON::PP->new->ascii(1)->encode([chr 0x10401])
234         => ["\ud801\udc01"]
235
236   latin1
237           $json = $json->latin1([$enable])
238
239           $enabled = $json->get_latin1
240
241       If $enable is true (or missing), then the encode method will encode the
242       resulting JSON text as latin1 (or iso-8859-1), escaping any characters
243       outside the code range 0..255.
244
245       If $enable is false, then the encode method will not escape Unicode
246       characters unless required by the JSON syntax or other flags.
247
248         JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
249         => ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)
250
251       See to "UNICODE HANDLING ON PERLS".
252
253   utf8
254           $json = $json->utf8([$enable])
255
256           $enabled = $json->get_utf8
257
258       If $enable is true (or missing), then the encode method will encode the
259       JSON result into UTF-8, as required by many protocols, while the decode
260       method expects to be handled an UTF-8-encoded string. Please note that
261       UTF-8-encoded strings do not contain any characters outside the range
262       0..255, they are thus useful for bytewise/binary I/O.
263
264       (In Perl 5.005, any character outside the range 0..255 does not exist.
265       See to "UNICODE HANDLING ON PERLS".)
266
267       In future versions, enabling this option might enable autodetection of
268       the UTF-16 and UTF-32 encoding families, as described in RFC4627.
269
270       If $enable is false, then the encode method will return the JSON string
271       as a (non-encoded) Unicode string, while decode expects thus a Unicode
272       string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be
273       done yourself, e.g. using the Encode module.
274
275       Example, output UTF-16BE-encoded JSON:
276
277         use Encode;
278         $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
279
280       Example, decode UTF-32LE-encoded JSON:
281
282         use Encode;
283         $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
284
285   pretty
286           $json = $json->pretty([$enable])
287
288       This enables (or disables) all of the "indent", "space_before" and
289       "space_after" flags in one call to generate the most readable (or most
290       compact) form possible.
291
292       Equivalent to:
293
294          $json->indent->space_before->space_after
295
296   indent
297           $json = $json->indent([$enable])
298
299           $enabled = $json->get_indent
300
301       The default indent space length is three.  You can use "indent_length"
302       to change the length.
303
304   space_before
305           $json = $json->space_before([$enable])
306
307           $enabled = $json->get_space_before
308
309       If $enable is true (or missing), then the "encode" method will add an
310       extra optional space before the ":" separating keys from values in JSON
311       objects.
312
313       If $enable is false, then the "encode" method will not add any extra
314       space at those places.
315
316       This setting has no effect when decoding JSON texts.
317
318       Example, space_before enabled, space_after and indent disabled:
319
320          {"key" :"value"}
321
322   space_after
323           $json = $json->space_after([$enable])
324
325           $enabled = $json->get_space_after
326
327       If $enable is true (or missing), then the "encode" method will add an
328       extra optional space after the ":" separating keys from values in JSON
329       objects and extra whitespace after the "," separating key-value pairs
330       and array members.
331
332       If $enable is false, then the "encode" method will not add any extra
333       space at those places.
334
335       This setting has no effect when decoding JSON texts.
336
337       Example, space_before and indent disabled, space_after enabled:
338
339          {"key": "value"}
340
341   relaxed
342           $json = $json->relaxed([$enable])
343
344           $enabled = $json->get_relaxed
345
346       If $enable is true (or missing), then "decode" will accept some
347       extensions to normal JSON syntax (see below). "encode" will not be
348       affected in anyway. Be aware that this option makes you accept invalid
349       JSON texts as if they were valid!. I suggest only to use this option to
350       parse application-specific files written by humans (configuration
351       files, resource files etc.)
352
353       If $enable is false (the default), then "decode" will only accept valid
354       JSON texts.
355
356       Currently accepted extensions are:
357
358       ·   list items can have an end-comma
359
360           JSON separates array elements and key-value pairs with commas. This
361           can be annoying if you write JSON texts manually and want to be
362           able to quickly append elements, so this extension accepts comma at
363           the end of such items not just between them:
364
365              [
366                 1,
367                 2, <- this comma not normally allowed
368              ]
369              {
370                 "k1": "v1",
371                 "k2": "v2", <- this comma not normally allowed
372              }
373
374       ·   shell-style '#'-comments
375
376           Whenever JSON allows whitespace, shell-style comments are
377           additionally allowed. They are terminated by the first carriage-
378           return or line-feed character, after which more white-space and
379           comments are allowed.
380
381             [
382                1, # this comment not allowed in JSON
383                   # neither this one...
384             ]
385
386   canonical
387           $json = $json->canonical([$enable])
388
389           $enabled = $json->get_canonical
390
391       If $enable is true (or missing), then the "encode" method will output
392       JSON objects by sorting their keys. This is adding a comparatively high
393       overhead.
394
395       If $enable is false, then the "encode" method will output key-value
396       pairs in the order Perl stores them (which will likely change between
397       runs of the same script).
398
399       This option is useful if you want the same data structure to be encoded
400       as the same JSON text (given the same overall settings). If it is
401       disabled, the same hash might be encoded differently even if contains
402       the same data, as key-value pairs have no inherent ordering in Perl.
403
404       This setting has no effect when decoding JSON texts.
405
406       If you want your own sorting routine, you can give a code referece or a
407       subroutine name to "sort_by". See to "JSON::PP OWN METHODS".
408
409   allow_nonref
410           $json = $json->allow_nonref([$enable])
411
412           $enabled = $json->get_allow_nonref
413
414       If $enable is true (or missing), then the "encode" method can convert a
415       non-reference into its corresponding string, number or null JSON value,
416       which is an extension to RFC4627. Likewise, "decode" will accept those
417       JSON values instead of croaking.
418
419       If $enable is false, then the "encode" method will croak if it isn't
420       passed an arrayref or hashref, as JSON texts must either be an object
421       or array. Likewise, "decode" will croak if given something that is not
422       a JSON object or array.
423
424          JSON::PP->new->allow_nonref->encode ("Hello, World!")
425          => "Hello, World!"
426
427   allow_unknown
428           $json = $json->allow_unknown ([$enable])
429
430           $enabled = $json->get_allow_unknown
431
432       If $enable is true (or missing), then "encode" will *not* throw an
433       exception when it encounters values it cannot represent in JSON (for
434       example, filehandles) but instead will encode a JSON "null" value.
435       Note that blessed objects are not included here and are handled
436       separately by c<allow_nonref>.
437
438       If $enable is false (the default), then "encode" will throw an
439       exception when it encounters anything it cannot encode as JSON.
440
441       This option does not affect "decode" in any way, and it is recommended
442       to leave it off unless you know your communications partner.
443
444   allow_blessed
445           $json = $json->allow_blessed([$enable])
446
447           $enabled = $json->get_allow_blessed
448
449       If $enable is true (or missing), then the "encode" method will not barf
450       when it encounters a blessed reference. Instead, the value of the
451       convert_blessed option will decide whether "null" ("convert_blessed"
452       disabled or no "TO_JSON" method found) or a representation of the
453       object ("convert_blessed" enabled and "TO_JSON" method found) is being
454       encoded. Has no effect on "decode".
455
456       If $enable is false (the default), then "encode" will throw an
457       exception when it encounters a blessed object.
458
459   convert_blessed
460           $json = $json->convert_blessed([$enable])
461
462           $enabled = $json->get_convert_blessed
463
464       If $enable is true (or missing), then "encode", upon encountering a
465       blessed object, will check for the availability of the "TO_JSON" method
466       on the object's class. If found, it will be called in scalar context
467       and the resulting scalar will be encoded instead of the object. If no
468       "TO_JSON" method is found, the value of "allow_blessed" will decide
469       what to do.
470
471       The "TO_JSON" method may safely call die if it wants. If "TO_JSON"
472       returns other blessed objects, those will be handled in the same way.
473       "TO_JSON" must take care of not causing an endless recursion cycle (==
474       crash) in this case. The name of "TO_JSON" was chosen because other
475       methods called by the Perl core (== not by the user of the object) are
476       usually in upper case letters and to avoid collisions with the
477       "to_json" function or method.
478
479       This setting does not yet influence "decode" in any way.
480
481       If $enable is false, then the "allow_blessed" setting will decide what
482       to do when a blessed object is found.
483
484   filter_json_object
485           $json = $json->filter_json_object([$coderef])
486
487       When $coderef is specified, it will be called from "decode" each time
488       it decodes a JSON object. The only argument passed to the coderef is a
489       reference to the newly-created hash. If the code references returns a
490       single scalar (which need not be a reference), this value (i.e. a copy
491       of that scalar to avoid aliasing) is inserted into the deserialised
492       data structure. If it returns an empty list (NOTE: not "undef", which
493       is a valid scalar), the original deserialised hash will be inserted.
494       This setting can slow down decoding considerably.
495
496       When $coderef is omitted or undefined, any existing callback will be
497       removed and "decode" will not change the deserialised hash in any way.
498
499       Example, convert all JSON objects into the integer 5:
500
501          my $js = JSON::PP->new->filter_json_object (sub { 5 });
502          # returns [5]
503          $js->decode ('[{}]'); # the given subroutine takes a hash reference.
504          # throw an exception because allow_nonref is not enabled
505          # so a lone 5 is not allowed.
506          $js->decode ('{"a":1, "b":2}');
507
508   filter_json_single_key_object
509           $json = $json->filter_json_single_key_object($key [=> $coderef])
510
511       Works remotely similar to "filter_json_object", but is only called for
512       JSON objects having a single key named $key.
513
514       This $coderef is called before the one specified via
515       "filter_json_object", if any. It gets passed the single value in the
516       JSON object. If it returns a single value, it will be inserted into the
517       data structure. If it returns nothing (not even "undef" but the empty
518       list), the callback from "filter_json_object" will be called next, as
519       if no single-key callback were specified.
520
521       If $coderef is omitted or undefined, the corresponding callback will be
522       disabled. There can only ever be one callback for a given key.
523
524       As this callback gets called less often then the "filter_json_object"
525       one, decoding speed will not usually suffer as much. Therefore, single-
526       key objects make excellent targets to serialise Perl objects into,
527       especially as single-key JSON objects are as close to the type-tagged
528       value concept as JSON gets (it's basically an ID/VALUE tuple). Of
529       course, JSON does not support this in any way, so you need to make sure
530       your data never looks like a serialised Perl hash.
531
532       Typical names for the single object key are "__class_whatever__", or
533       "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or even
534       things like "__class_md5sum(classname)__", to reduce the risk of
535       clashing with real hashes.
536
537       Example, decode JSON objects of the form "{ "__widget__" => <id> }"
538       into the corresponding $WIDGET{<id>} object:
539
540          # return whatever is in $WIDGET{5}:
541          JSON::PP
542             ->new
543             ->filter_json_single_key_object (__widget__ => sub {
544                   $WIDGET{ $_[0] }
545                })
546             ->decode ('{"__widget__": 5')
547
548          # this can be used with a TO_JSON method in some "widget" class
549          # for serialisation to json:
550          sub WidgetBase::TO_JSON {
551             my ($self) = @_;
552
553             unless ($self->{id}) {
554                $self->{id} = ..get..some..id..;
555                $WIDGET{$self->{id}} = $self;
556             }
557
558             { __widget__ => $self->{id} }
559          }
560
561   shrink
562           $json = $json->shrink([$enable])
563
564           $enabled = $json->get_shrink
565
566       In JSON::XS, this flag resizes strings generated by either "encode" or
567       "decode" to their minimum size possible.  It will also try to downgrade
568       any strings to octet-form if possible.
569
570       In JSON::PP, it is noop about resizing strings but tries
571       "utf8::downgrade" to the returned string by "encode".  See to utf8.
572
573       See to "OBJECT-ORIENTED INTERFACE" in JSON::XS
574
575   max_depth
576           $json = $json->max_depth([$maximum_nesting_depth])
577
578           $max_depth = $json->get_max_depth
579
580       Sets the maximum nesting level (default 512) accepted while encoding or
581       decoding. If a higher nesting level is detected in JSON text or a Perl
582       data structure, then the encoder and decoder will stop and croak at
583       that point.
584
585       Nesting level is defined by number of hash- or arrayrefs that the
586       encoder needs to traverse to reach a given point or the number of "{"
587       or "[" characters without their matching closing parenthesis crossed to
588       reach a given character in a string.
589
590       If no argument is given, the highest possible setting will be used,
591       which is rarely useful.
592
593       See "SSECURITY CONSIDERATIONS" in JSON::XS for more info on why this is
594       useful.
595
596       When a large value (100 or more) was set and it de/encodes a deep
597       nested object/text, it may raise a warning 'Deep recursion on
598       subroutin' at the perl runtime phase.
599
600   max_size
601           $json = $json->max_size([$maximum_string_size])
602
603           $max_size = $json->get_max_size
604
605       Set the maximum length a JSON text may have (in bytes) where decoding
606       is being attempted. The default is 0, meaning no limit. When "decode"
607       is called on a string that is longer then this many bytes, it will not
608       attempt to decode the string but throw an exception. This setting has
609       no effect on "encode" (yet).
610
611       If no argument is given, the limit check will be deactivated (same as
612       when 0 is specified).
613
614       See "SSECURITY CONSIDERATIONS" in JSON::XS for more info on why this is
615       useful.
616
617   encode
618           $json_text = $json->encode($perl_scalar)
619
620       Converts the given Perl data structure (a simple scalar or a reference
621       to a hash or array) to its JSON representation. Simple scalars will be
622       converted into JSON string or number sequences, while references to
623       arrays become JSON arrays and references to hashes become JSON objects.
624       Undefined Perl values (e.g. "undef") become JSON "null" values.
625       References to the integers 0 and 1 are converted into "true" and
626       "false".
627
628   decode
629           $perl_scalar = $json->decode($json_text)
630
631       The opposite of "encode": expects a JSON text and tries to parse it,
632       returning the resulting simple scalar or reference. Croaks on error.
633
634       JSON numbers and strings become simple Perl scalars. JSON arrays become
635       Perl arrayrefs and JSON objects become Perl hashrefs. "true" becomes 1
636       ("JSON::true"), "false" becomes 0 ("JSON::false") and "null" becomes
637       "undef".
638
639   decode_prefix
640           ($perl_scalar, $characters) = $json->decode_prefix($json_text)
641
642       This works like the "decode" method, but instead of raising an
643       exception when there is trailing garbage after the first JSON object,
644       it will silently stop parsing there and return the number of characters
645       consumed so far.
646
647          JSON->new->decode_prefix ("[1] the tail")
648          => ([], 3)
649

INCREMENTAL PARSING

651       Most of this section are copied and modified from "INCREMENTAL PARSING"
652       in JSON::XS.
653
654       In some cases, there is the need for incremental parsing of JSON texts.
655       This module does allow you to parse a JSON stream incrementally.  It
656       does so by accumulating text until it has a full JSON object, which it
657       then can decode. This process is similar to using "decode_prefix" to
658       see if a full JSON object is available, but is much more efficient (and
659       can be implemented with a minimum of method calls).
660
661       This module will only attempt to parse the JSON text once it is sure it
662       has enough text to get a decisive result, using a very simple but truly
663       incremental parser. This means that it sometimes won't stop as early as
664       the full parser, for example, it doesn't detect parenthese mismatches.
665       The only thing it guarantees is that it starts decoding as soon as a
666       syntactically valid JSON text has been seen. This means you need to set
667       resource limits (e.g. "max_size") to ensure the parser will stop
668       parsing in the presence if syntax errors.
669
670       The following methods implement this incremental parser.
671
672   incr_parse
673           $json->incr_parse( [$string] ) # void context
674
675           $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
676
677           @obj_or_empty = $json->incr_parse( [$string] ) # list context
678
679       This is the central parsing function. It can both append new text and
680       extract objects from the stream accumulated so far (both of these
681       functions are optional).
682
683       If $string is given, then this string is appended to the already
684       existing JSON fragment stored in the $json object.
685
686       After that, if the function is called in void context, it will simply
687       return without doing anything further. This can be used to add more
688       text in as many chunks as you want.
689
690       If the method is called in scalar context, then it will try to extract
691       exactly one JSON object. If that is successful, it will return this
692       object, otherwise it will return "undef". If there is a parse error,
693       this method will croak just as "decode" would do (one can then use
694       "incr_skip" to skip the errornous part). This is the most common way of
695       using the method.
696
697       And finally, in list context, it will try to extract as many objects
698       from the stream as it can find and return them, or the empty list
699       otherwise. For this to work, there must be no separators between the
700       JSON objects or arrays, instead they must be concatenated back-to-back.
701       If an error occurs, an exception will be raised as in the scalar
702       context case. Note that in this case, any previously-parsed JSON texts
703       will be lost.
704
705       Example: Parse some JSON arrays/objects in a given string and return
706       them.
707
708           my @objs = JSON->new->incr_parse ("[5][7][1,2]");
709
710   incr_text
711           $lvalue_string = $json->incr_text
712
713       This method returns the currently stored JSON fragment as an lvalue,
714       that is, you can manipulate it. This only works when a preceding call
715       to "incr_parse" in scalar context successfully returned an object.
716       Under all other circumstances you must not call this function (I mean
717       it.  although in simple tests it might actually work, it will fail
718       under real world conditions). As a special exception, you can also call
719       this method before having parsed anything.
720
721       This function is useful in two cases: a) finding the trailing text
722       after a JSON object or b) parsing multiple JSON objects separated by
723       non-JSON text (such as commas).
724
725           $json->incr_text =~ s/\s*,\s*//;
726
727       In Perl 5.005, "lvalue" attribute is not available.  You must write
728       codes like the below:
729
730           $string = $json->incr_text;
731           $string =~ s/\s*,\s*//;
732           $json->incr_text( $string );
733
734   incr_skip
735           $json->incr_skip
736
737       This will reset the state of the incremental parser and will remove the
738       parsed text from the input buffer. This is useful after "incr_parse"
739       died, in which case the input buffer and incremental parser state is
740       left unchanged, to skip the text parsed so far and to reset the parse
741       state.
742
743   incr_reset
744           $json->incr_reset
745
746       This completely resets the incremental parser, that is, after this
747       call, it will be as if the parser had never parsed anything.
748
749       This is useful if you want ot repeatedly parse JSON objects and want to
750       ignore any trailing data, which means you have to reset the parser
751       after each successful decode.
752
753       See to "INCREMENTAL PARSING" in JSON::XS for examples.
754

JSON::PP OWN METHODS

756   allow_singlequote
757           $json = $json->allow_singlequote([$enable])
758
759       If $enable is true (or missing), then "decode" will accept JSON strings
760       quoted by single quotations that are invalid JSON format.
761
762           $json->allow_singlequote->decode({"foo":'bar'});
763           $json->allow_singlequote->decode({'foo':"bar"});
764           $json->allow_singlequote->decode({'foo':'bar'});
765
766       As same as the "relaxed" option, this option may be used to parse
767       application-specific files written by humans.
768
769   allow_barekey
770           $json = $json->allow_barekey([$enable])
771
772       If $enable is true (or missing), then "decode" will accept bare keys of
773       JSON object that are invalid JSON format.
774
775       As same as the "relaxed" option, this option may be used to parse
776       application-specific files written by humans.
777
778           $json->allow_barekey->decode('{foo:"bar"}');
779
780   allow_bignum
781           $json = $json->allow_bignum([$enable])
782
783       If $enable is true (or missing), then "decode" will convert the big
784       integer Perl cannot handle as integer into a Math::BigInt object and
785       convert a floating number (any) into a Math::BigFloat.
786
787       On the contary, "encode" converts "Math::BigInt" objects and
788       "Math::BigFloat" objects into JSON numbers with "allow_blessed" enable.
789
790          $json->allow_nonref->allow_blessed->allow_bignum;
791          $bigfloat = $json->decode('2.000000000000000000000000001');
792          print $json->encode($bigfloat);
793          # => 2.000000000000000000000000001
794
795       See to "MAPPING" in JSON::XS aboout the normal conversion of JSON
796       number.
797
798   loose
799           $json = $json->loose([$enable])
800
801       The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON
802       strings and the module doesn't allow to "decode" to these (except for
803       \x2f).  If $enable is true (or missing), then "decode"  will accept
804       these unescaped strings.
805
806           $json->loose->decode(qq|["abc
807                                          def"]|);
808
809       See "SSECURITY CONSIDERATIONS" in JSON::XS.
810
811   escape_slash
812           $json = $json->escape_slash([$enable])
813
814       According to JSON Grammar, slash (U+002F) is escaped. But default
815       JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
816
817       If $enable is true (or missing), then "encode" will escape slashes.
818
819   indent_length
820           $json = $json->indent_length($length)
821
822       JSON::XS indent space length is 3 and cannot be changed.  JSON::PP set
823       the indent space length with the given $length.  The default is 3. The
824       acceptable range is 0 to 15.
825
826   sort_by
827           $json = $json->sort_by($function_name)
828           $json = $json->sort_by($subroutine_ref)
829
830       If $function_name or $subroutine_ref are set, its sort routine are used
831       in encoding JSON objects.
832
833          $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
834          # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
835
836          $js = $pc->sort_by('own_sort')->encode($obj);
837          # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
838
839          sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
840
841       As the sorting routine runs in the JSON::PP scope, the given subroutine
842       name and the special variables $a, $b will begin 'JSON::PP::'.
843
844       If $integer is set, then the effect is same as "canonical" on.
845

INTERNAL

847       For developers.
848
849       PP_encode_box
850           Returns
851
852                   {
853                       depth        => $depth,
854                       indent_count => $indent_count,
855                   }
856
857       PP_decode_box
858           Returns
859
860                   {
861                       text    => $text,
862                       at      => $at,
863                       ch      => $ch,
864                       len     => $len,
865                       depth   => $depth,
866                       encoding      => $encoding,
867                       is_valid_utf8 => $is_valid_utf8,
868                   };
869

MAPPING

871       This section is copied from JSON::XS and modified to "JSON::PP".
872       JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
873
874       See to "MAPPING" in JSON::XS.
875
876   JSON -> PERL
877       object
878           A JSON object becomes a reference to a hash in Perl. No ordering of
879           object keys is preserved (JSON does not preserver object key
880           ordering itself).
881
882       array
883           A JSON array becomes a reference to an array in Perl.
884
885       string
886           A JSON string becomes a string scalar in Perl - Unicode codepoints
887           in JSON are represented by the same codepoints in the Perl string,
888           so no manual decoding is necessary.
889
890       number
891           A JSON number becomes either an integer, numeric (floating point)
892           or string scalar in perl, depending on its range and any fractional
893           parts. On the Perl level, there is no difference between those as
894           Perl handles all the conversion details, but an integer may take
895           slightly less memory and might represent more values exactly than
896           floating point numbers.
897
898           If the number consists of digits only, "JSON" will try to represent
899           it as an integer value. If that fails, it will try to represent it
900           as a numeric (floating point) value if that is possible without
901           loss of precision. Otherwise it will preserve the number as a
902           string value (in which case you lose roundtripping ability, as the
903           JSON number will be re-encoded toa JSON string).
904
905           Numbers containing a fractional or exponential part will always be
906           represented as numeric (floating point) values, possibly at a loss
907           of precision (in which case you might lose perfect roundtripping
908           ability, but the JSON number will still be re-encoded as a JSON
909           number).
910
911           Note that precision is not accuracy - binary floating point values
912           cannot represent most decimal fractions exactly, and when
913           converting from and to floating point, "JSON" only guarantees
914           precision up to but not including the leats significant bit.
915
916           When "allow_bignum" is enable, the big integers and the numeric can
917           be optionally converted into Math::BigInt and Math::BigFloat
918           objects.
919
920       true, false
921           These JSON atoms become "JSON::PP::true" and "JSON::PP::false",
922           respectively. They are overloaded to act almost exactly like the
923           numbers 1 and 0. You can check wether a scalar is a JSON boolean by
924           using the "JSON::is_bool" function.
925
926              print JSON::PP::true . "\n";
927               => true
928              print JSON::PP::true + 1;
929               => 1
930
931              ok(JSON::true eq  '1');
932              ok(JSON::true == 1);
933
934           "JSON" will install these missing overloading features to the
935           backend modules.
936
937       null
938           A JSON null atom becomes "undef" in Perl.
939
940           "JSON::PP::null" returns "unddef".
941
942   PERL -> JSON
943       The mapping from Perl to JSON is slightly more difficult, as Perl is a
944       truly typeless language, so we can only guess which JSON type is meant
945       by a Perl value.
946
947       hash references
948           Perl hash references become JSON objects. As there is no inherent
949           ordering in hash keys (or JSON objects), they will usually be
950           encoded in a pseudo-random order that can change between runs of
951           the same program but stays generally the same within a single run
952           of a program. "JSON" optionally sort the hash keys (determined by
953           the canonical flag), so the same datastructure will serialise to
954           the same JSON text (given same settings and version of JSON::XS),
955           but this incurs a runtime overhead and is only rarely useful, e.g.
956           when you want to compare some JSON text against another for
957           equality.
958
959       array references
960           Perl array references become JSON arrays.
961
962       other references
963           Other unblessed references are generally not allowed and will cause
964           an exception to be thrown, except for references to the integers 0
965           and 1, which get turned into "false" and "true" atoms in JSON. You
966           can also use "JSON::false" and "JSON::true" to improve readability.
967
968              to_json [\0,JSON::PP::true]      # yields [false,true]
969
970       JSON::PP::true, JSON::PP::false, JSON::PP::null
971           These special values become JSON true and JSON false values,
972           respectively. You can also use "\1" and "\0" directly if you want.
973
974           JSON::PP::null returns "undef".
975
976       blessed objects
977           Blessed objects are not directly representable in JSON. See the
978           "allow_blessed" and "convert_blessed" methods on various options on
979           how to deal with this: basically, you can choose between throwing
980           an exception, encoding the reference as if it weren't blessed, or
981           provide your own serialiser method.
982
983           See to convert_blessed.
984
985       simple scalars
986           Simple Perl scalars (any scalar that is not a reference) are the
987           most difficult objects to encode: JSON::XS and JSON::PP will encode
988           undefined scalars as JSON "null" values, scalars that have last
989           been used in a string context before encoding as JSON strings, and
990           anything else as number value:
991
992              # dump as number
993              encode_json [2]                      # yields [2]
994              encode_json [-3.0e17]                # yields [-3e+17]
995              my $value = 5; encode_json [$value]  # yields [5]
996
997              # used as string, so dump as string
998              print $value;
999              encode_json [$value]                 # yields ["5"]
1000
1001              # undef becomes null
1002              encode_json [undef]                  # yields [null]
1003
1004           You can force the type to be a string by stringifying it:
1005
1006              my $x = 3.1; # some variable containing a number
1007              "$x";        # stringified
1008              $x .= "";    # another, more awkward way to stringify
1009              print $x;    # perl does it for you, too, quite often
1010
1011           You can force the type to be a number by numifying it:
1012
1013              my $x = "3"; # some variable containing a string
1014              $x += 0;     # numify it, ensuring it will be dumped as a number
1015              $x *= 1;     # same thing, the choise is yours.
1016
1017           You can not currently force the type in other, less obscure, ways.
1018
1019           Note that numerical precision has the same meaning as under Perl
1020           (so binary to decimal conversion follows the same rules as in Perl,
1021           which can differ to other languages). Also, your perl interpreter
1022           might expose extensions to the floating point numbers of your
1023           platform, such as infinities or NaN's - these cannot be represented
1024           in JSON, and it is an error to pass those in.
1025
1026       Big Number
1027           When "allow_bignum" is enable, "encode" converts "Math::BigInt"
1028           objects and "Math::BigFloat" objects into JSON numbers.
1029

UNICODE HANDLING ON PERLS

1031       If you do not know about Unicode on Perl well, please check "A FEW
1032       NOTES ON UNICODE AND PERL" in JSON::XS.
1033
1034   Perl 5.8 and later
1035       Perl can handle Unicode and the JSON::PP de/encode methods also work
1036       properly.
1037
1038           $json->allow_nonref->encode(chr hex 3042);
1039           $json->allow_nonref->encode(chr hex 12345);
1040
1041       Reuturns "\u3042" and "\ud808\udf45" respectively.
1042
1043           $json->allow_nonref->decode('"\u3042"');
1044           $json->allow_nonref->decode('"\ud808\udf45"');
1045
1046       Returns UTF-8 encoded strings with UTF8 flag, regarded as "U+3042" and
1047       "U+12345".
1048
1049       Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in "join"
1050       was broken, so JSON::PP wraps the "join" with a subroutine. Thus
1051       JSON::PP works slow in the versions.
1052
1053   Perl 5.6
1054       Perl can handle Unicode and the JSON::PP de/encode methods also work.
1055
1056   Perl 5.005
1057       Perl 5.005 is a byte sementics world -- all strings are sequences of
1058       bytes.  That means the unicode handling is not available.
1059
1060       In encoding,
1061
1062           $json->allow_nonref->encode(chr hex 3042);  # hex 3042 is 12354.
1063           $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
1064
1065       Returns "B" and "E", as "chr" takes a value more than 255, it treats as
1066       "$value % 256", so the above codes are equivalent to :
1067
1068           $json->allow_nonref->encode(chr 66);
1069           $json->allow_nonref->encode(chr 69);
1070
1071       In decoding,
1072
1073           $json->decode('"\u00e3\u0081\u0082"');
1074
1075       The returned is a byte sequence "0xE3 0x81 0x82" for UTF-8 encoded
1076       japanese character ("HIRAGANA LETTER A").  And if it is represented in
1077       Unicode code point, "U+3042".
1078
1079       Next,
1080
1081           $json->decode('"\u3042"');
1082
1083       We ordinary expect the returned value is a Unicode character "U+3042".
1084       But here is 5.005 world. This is "0xE3 0x81 0x82".
1085
1086           $json->decode('"\ud808\udf45"');
1087
1088       This is not a character "U+12345" but bytes - "0xf0 0x92 0x8d 0x85".
1089

TODO

1091       speed
1092       memory saving
1093

SEE ALSO

1095       Most of the document are copied and modified from JSON::XS doc.
1096
1097       JSON::XS
1098
1099       RFC4627 (<http://www.ietf.org/rfc/rfc4627.txt>)
1100

AUTHOR

1102       Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
1103
1105       Copyright 2007-2013 by Makamaka Hannyaharamitu
1106
1107       This library is free software; you can redistribute it and/or modify it
1108       under the same terms as Perl itself.
1109
1110
1111
1112perl v5.16.3                      2013-03-13                       JSON::PP(3)
Impressum