1JSON::backportPP(3)   User Contributed Perl Documentation  JSON::backportPP(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.27200
33
34       JSON::XS 2.27 (~2.30) compatible.
35

DESCRIPTION

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

FUNCTIONAL INTERFACE

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

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

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

METHODS

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

INCREMENTAL PARSING

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

JSON::PP OWN METHODS

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

INTERNAL

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

MAPPING

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

UNICODE HANDLING ON PERLS

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

TODO

1087       speed
1088       memory saving
1089

SEE ALSO

1091       Most of the document are copied and modified from JSON::XS doc.
1092
1093       JSON::XS
1094
1095       RFC4627 (<http://www.ietf.org/rfc/rfc4627.txt>)
1096

AUTHOR

1098       Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
1099
1101       Copyright 2007-2012 by Makamaka Hannyaharamitu
1102
1103       This library is free software; you can redistribute it and/or modify it
1104       under the same terms as Perl itself.
1105
1106
1107
1108perl v5.16.3                      2013-05-23               JSON::backportPP(3)
Impressum